ajax 跨域解决方案

有的浏览器不支持跨域访问,为ie8。 那么我们可以通过重新构造一个新的可以url来支持跨域获取资源,代码如下。

var url = forexample.test.com.cn;

if (!$.support.cors) {
var start = url.indexOf('.test.com.cn') + 12; //12 为 ".test.com.cn"的长度。
    var callName = url.substring(start);
proxyUrl = url.substring(0, start);
url =
window.location.protocol + "//" + window.location.host + '/proxy/?targetUrl=' + callName;
}
$.ajax({
type: 'GET', // or 'POST'
url: url,
dataType: "json",
contentType: "application/json",
beforeSend: function(request) {
},
success: function(res, status, xhr) {
},
error: function(res) {
}
});


需要注意的是你的后台也要配置跨域访问方式

 
posted @ 2016-05-07 16:44  爱学习的小赵同学  阅读(110)  评论(0)    收藏  举报