为了数据安全,默认情况下ajax请求是不支持跨域访问。
但是可以通过以下方法让ajax接收跨域API地址
第一种:JSONP比较老,较简单的请求可以考虑使用。
JS代码
$(function () { $.ajax({ type: "GET", cache: false, url: "http://jrj.ecio.cc/API/Article/GetINFFAList", dataType: "jsonp", jsonpCallback: "successCallback", success: function (msg) { alert(msg.errMsg); }, }); }); function successCallback() { alert('aa'); }
后台代码注意事项
后端在数据返回时,一定要加上jsonpCallback所指定的方法名,例如:Response.Write("successCallback("+data+")");
否则就会出现“Uncaught SyntaxError: Unexpected token ”这样的错误。
第二种:CORS
function createCORSRequest(method, url) { var xhr = new XMLHttpRequest(); if ("withCredentials" in xhr) { // 此时即支持CORS的情况 // 检查XMLHttpRequest对象是否有“withCredentials”属性 // “withCredentials”仅存在于XMLHTTPRequest2对象里 xhr.open(method, url, true); } else if (typeof!= "undefined") { // 否则检查是否支持XDomainRequest,IE8和IE9支持 // XDomainRequest仅存在于IE中,是IE用于支持CORS请求的方式 xhr = new XDomainRequest(); xhr.open(method, url); } else { // 否则,浏览器不支持CORS xhr = null; } return xhr; } var xhr = createCORSRequest('GET', url); if (!xhr) { throw new Error('CORS not supported'); }
HTTP响应表头设置
添加“Access-Control-Allow-Origin”值为“*”即可。
还有其他的一些方法:iframe、flash等
补充:如果为post提交,还需添加响应头
Access-Control-Allow-Headers :x-requested-with,content-type
Access-Control-Allow-Methods:POST