<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>JSONP跨域</title> </head> <body> <div> <button id="btn">點擊</button> </div> <script> function handleResponse(responent) { console.log(responent) } </script> </body> <script> window.onload = function () { let btn = document.getElementById('btn'); btn.addEventListener('click', function () { var scritpt = document.createElement('script'); scritpt.src = 'https://api.douban.com/v2/book/search?q=javascript&count=1&callback=handleResponse'; document.body.insertBefore(scritpt, document.body.firstChild); }); } </script> </html> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>jq-JSONP跨域</title> <script src="./../../jq/jquery.js"></script> </head> <body> <div> <button id="btn">點擊</button> </div> </body> <script> $(function () { $("#btn").on('click', function () { $.ajax({ async: true, url: "https://api.douban.com/v2/book/search", type: "GET", dataType: 'jsonp', //返回的數據類型,設置成jsonp方式 jsonp: 'callback', // 指定一個參數名稱來覆蓋默認的jsonp 回調參數名 callback jsonpCallback: "handleResponse", data: { q: "javascript", count: 1 }, success: function (response, status, xhr) { console.log(response) console.log(status) console.log(xhr) } }) }) }) </script> </html>
http://www.javashuo.com/article/p-otaoxebe-hx.htmljavascript