javascript跨域(.net4.0环境)

服务器端设置:
 

 Response.ContentType = "text/plain";
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
Response.Write("{\"id\":0}"); 

客户端js:

  $(function () {
if ($.browser.msie && parseInt($.browser.version, 10) >= 8 && window.XDomainRequest) {
//ie下跨域
var xdr = new XDomainRequest();

xdr.onload = function (e) {
var data = $.parseJSON(xdr.responseText);
if (data == null || typeof (data) == 'undefined') {
data = $.parseJSON(data.firstChild.textContent);
}
//success
alert(data.id);
};
xdr.onerror = function (e) {
//error
alert('error');
}

xdr.open("POST", url); //get,post都跨域
xdr.send();
} else {
//chrome,ff 跨域
$.ajax({
url:url , //
cache: false,
data: {},
type:'GET',
dataType: 'json',
success: function (data) {
alert(data.id);
},
error: function (e) {
alert(e.statusText);
}
})
}
})


使用jsonp实现跨域:

js代码:

//注意,我们使用 ? 作为回调函数名,而非真实的函数名。因为 jQuery 会用生成的函数名替换 ? 
jQuery.getJSON(url+"?callback=?", function (data) {
alert("ID: " + data.id);
});

服务器端:

Response.ContentType = "text/plain";
Response.Write(Request.QueryString["callback"] + "({\"id\":0})");


http://www.ibm.com/developerworks/cn/web/wa-aj-jsonp1/index.html

posted on 2011-12-01 11:48  BarneyZhang  阅读(368)  评论(0编辑  收藏  举报

导航