JavaScript解决API请求时的跨域处理问题
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>JSONP实现跨域访问</title> 6 </head> 7 <body> 8 <div id="mydiv"> 9 <button id="btn">click</button> 10 </div> 11 </body> 12 <script type="text/javascript"> 13 function handleResponse(response){ 14 console.log(response); 15 var getvalue=response.data; 16 console.log(response.data.city); 17 } 18 </script> 19 <script type="text/javascript"> 20 window.onload = function() { 21 var oBtn = document.getElementById('btn'); 22 oBtn.onclick = function() { 23 var script = document.createElement("script"); 24 script.src = "http://wthrcdn.etouch.cn/weather_mini?city=北京&callback=handleResponse"; 25 document.body.insertBefore(script, document.body.firstChild); 26 }; 27 28 }; 29 </script> 30 </html>
最后控制台输出返回jsonp数据如下