ajax在跨域get的时候会出现如标题所示的error get本地文件就不会 见如下代码
//get 本地 $.ajax({ url:"http://localhost/tickets/json/api_airport.json",type:'GET',dataType:"json",success:function(data){console.log(data.results.result[1].category);} });
//跨域get $.ajax({ url:"http://api.master18.tiket.com/search/autocomplete/hotel?q=mah&token=90d2fad44172390b11527557e6250e50&secretkey=83e2f0484edbd2ad6fc9888c1e30ea44&output=json",crossDomain:true,beforeSend: function(x) { if(x && x.overrideMimeType) { x.overrideMimeType("application/j-son;charset=UTF-8"); } },success:function(data){console.log("Success");} });
<?PHP // File Name: proxy.PHP if (!isset($_GET['url'])) die(); $url = urldecode($_GET['url']); $url = 'http://' . str_replace('http://','',$url); // Avoid accessing the file system echo file_get_contents($url);
ajax改为:
$.ajax({ url:"proxy.PHP",data: "url=http%3A%2F%2Fapi.master18.tiket.com%2Fsearch%2Fautocomplete%2Fhotel%3Fq%3Dmah%26token%3D90d2fad44172390b11527557e6250e50% 26secretkey%3D83e2f0 484edbd2ad6fc9888c1e30ea44%26output%3Djson",success:function(data){console.log(data.results.result[1].category);} });
And the reason:
You're getting this error because of XMLHttpRequest same origin policy,which basically boils down to a restriction of ajax requests to URLs with a different port,domain or protocol. This restriction is in place to prevent cross-site scripting (XSS) attacks.
原文链接:https://www.f2er.com/ajax/165391.html