第一次代碼中用json請求數據
<html> <meta charset="utf8"> <head> </head> <body> <input type="button" value="獲取JSON數據" onclick="getInfo()" /> </body> <script src="jquery-3.0.0.js"></script> <script> function getInfo(){ $.ajax({ type:"post", url:"https://kycp5.com/lotteryV2/lotV2Op.do?lotCode=CQSSC", async:true, dataType:"json", success: function(data){ data = JSON.parse(data); console.log(data); } }) } </script> </html>
報的錯誤是
XMLHttpRequest cannot load https://kycp5.com/lotteryV2/lotV2Op.do?lotCode=CQSSC. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
第二次代碼中用jsonp請求數據
<html> <meta charset="utf8"> <head> </head> <body> <input type="button" value="獲取JSON數據" onclick="getInfo()" /> </body> <script src="jquery-3.0.0.js"></script> <script> function getInfo(){ $.ajax({ type:"post", url:"https://kycp5.com/lotteryV2/lotV2Op.do?lotCode=CQSSC", async:true, dataType:"jsonp", success: function(data){ data = JSON.parse(data); console.log(data); } }) } </script> </html>
報的錯誤是
從網上搜到的解釋
請求到數據是一個純Json格式的話,是不能用Jsonp方式調用的,
支持Jsonp方式的url返回的一定是js腳本,一般是一句函數調用,
請注意第二種方法中報的錯是callback=,=號后面的就是你得到的,
callback是客戶端頁面定義的函數名,JSONP方式會在返回的
Javascript代碼里面調用這個函數,JSON數據是當做參數傳入方法的
而不是直接返回一個json。
這個地址不支持jsonp,請求來的數據是json,瀏覽器要把當做Javascript
來解析,遇到 ":" 就報錯了。
如果這個地址支持JSONP,應該返回Javascript代碼,在代碼里面調用
callback函數才對。
API出現增強富web應用開發的體驗,曾經想通過跨域請求api非常困難
可以使用json-p這樣的技術(有安全限制)或者自己搭建服務器。
跨域資源共享CORS是一種W3C的規范,允許瀏覽器進行跨域通信,
通過設置XMLHttpRequest對象,CORS允許開發者像發起同域請求
那樣發起跨域請求。
A網站想要訪問B網站上的一些數據,這種請求是被同源策略所禁止的,
然而,使用CORS,B網站增加些特殊響應頭可以允許來自A網站的請求。
因此,使用CORS需要服務器和客戶端之間相互了解,幸運的是,
如果你是一位客戶端開發者,你可以忽略里面的很多細節。
使用javascript進行跨域請求
1、創建XMLHttpRequest對象
chorme瀏覽器,火狐,Opera和Safari都使用XMLHttpRequest對象。
Internet Explorer使用XDomainRequest對象,有和XMLHttpRequest對象
差不多的功能,但是增加了額外的安全防范措施。
有個輔助方法來兼容不同瀏覽器
1 function createCORSRequest(method, url) { 2 var xhr = new XMLHttpRequest(); 3 if ("withCredentials" in xhr) { 4 5 // Check if the XMLHttpRequest object has a "withCredentials" property. 6 // "withCredentials" only exists on XMLHTTPRequest2 objects. 7 // "withCredentials"只存在XMLHTTPRequest2對象中 8 xhr.open(method, url, true); 9 10 } else if (typeof XDomainRequest != "undefined") { 11 12 // Otherwise, check if XDomainRequest. 13 // XDomainRequest only exists in IE, and is IE's way of making CORS requests. 14 xhr = new XDomainRequest(); 15 xhr.open(method, url); 16 17 } else { 18 19 // Otherwise, CORS is not supported by the browser. 20 xhr = null; 21 22 } 23 return xhr; 24 } 25 26 var xhr = createCORSRequest('GET', url); 27 if (!xhr) { 28 throw new Error('CORS not supported'); 29 }