jsonp跨域请求

复习一下jsonp跨域请求 

代码如下

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <title></title>
 5     <script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
 6 </head>
 7 <body>
 8     <div id="mydiv">
 9         <button id="btn1">跨域失败</button>
10         <button id="btn">JSONP实现跨域</button>
11         <button id="btn2">JQ $.ajax实现</button>
12         <button id="btn3">JQ $.getJSON()实现</button>
13     </div>
14 </body>
15 
16 <script>
17     
18     // jsonp callback函数
19     function handleResponse(response){
20                 console.log(response);
21             }
22 
23     //jq $.ajax callback函数
24     function suc(){
25         alert('success!');
26     }
27 
28     //原生写法
29     var oBtn1 = document.getElementById('btn1');
30     oBtn1.onclick = function(){
31         var xhr = new XMLHttpRequest();
32         xhr.onreadystatechange = function(){
33             if (xhr.readyState == 4 && xhr.status == 200) {
34                 alert(xhr.responseText);
35             }
36         }
37         xhr.open('get','https://api.douban.com/v2/book/search?q=javascript&count=1',true);
38         xhr.send();
39     }
40 
41     //jsonp 原理方法
42     var oBtn = document.getElementById('btn');
43         oBtn.onclick = function(){
44         var script = document.createElement("script");
45         script.src = "https://api.douban.com/v2/book/search?q=javascript&count=1&callback=handleResponse";
46         document.body.insertBefore(script,document.body.firstChild);
47     }
48         
49     //jq提供的ajax方法
50     $('#btn2').click(function(){
51         $.ajax({
52             async : true,
53             url : "https://api.douban.com/v2/book/search",
54             type : "GET",
55             dataType : "jsonp", //返回的数据类型,设置为jsonp为跨域请求
56             jsonp: "callback", //指定一个查询参数名称来覆盖默认的jsonp回调参数名callback
57             jsonpCallback: "suc", //设置回调函数
58             data : {
59                 q : "生命",
60                 count : 10
61             },
62             success: function(response, status, xhr){
63                 console.log("状态为:" + status + ",状态是:" + xhr.statusText);
64                 console.log(response);
65             }
66         })
67     })
68 
69 
70     //jq提供的简单的方法
71     // $.getJSON(url, data, success)
72     //这里的data参数可以直接拼接到url后面,最后不要忘记加上callback=?
73     //如:     $.getJSON("https://api.douban.com/v2/book/search?q=***&count=*&callback=?", function())
74     $('#btn3').click(function(){
75           $.getJSON("https://api.douban.com/v2/book/search?callback=?",
76               {
77                   q: "生活",
78                   count: 20
79               }
80               ,
81               function(data){
82                   console.log(data);
83               }
84           )
85     })
86 
87 
88 
89 </script>
90 </html>

猜你喜欢

转载自www.cnblogs.com/qichuang/p/9262806.html