Ajax跨域get出现的Not allowed by Access-Control-Allow-Origin

来源:互联网 发布:mac命令行终端软件 编辑:程序博客网 时间:2024/06/05 20:12

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",            type:'GET',            crossDomain:true,            beforeSend: function(x) {                if(x && x.overrideMimeType) {                    x.overrideMimeType("application/j-son;charset=UTF-8");                }            },            success:function(data){console.log("Success");}        });



如上跨域get error的解决办法 目测我用的是增加一个proxy.php文件 先php文件跨域get 然后ajax从PHP中get数据

<?php// File Name: proxy.phpif (!isset($_GET['url'])) die();$url = urldecode($_GET['url']);$url = 'http://' . str_replace('http://', '', $url); // Avoid accessing the file systemecho 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%3D83e2f0484edbd2ad6fc9888c1e30ea44%26output%3Djson",    type:'GET',    dataType:"json",    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.






0 0