如果是phonegap/cordova打包的,可以修改config.xml的access节点达到跨域的目的:
<access origin="*" />
如果是网站,可以有下面的实现方法:
一、使用代理
在你当前域中架设一个服务端B,通过这个服务端B去请求另一个域A。你的前台js请求服务端B
这个大家都知道,实际上是将请求参数拼接到url上,通过GET请求的。受url长度的限制,请求参数的体积不能太大
jsonp的实质是一句js代码,而不是{开头、}结尾的JSON字符串
三、修改web.config文件(Asp.Net)
整个应用都支持跨域的请求,需要部署到IIS中才能使用。
web.config:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/>
<add name="Access-Control-Allow-Headers" value="x-requested-with,content-type"/>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
$.ajax({
url: "http://localhost/CROS/handler.ashx",
xhrFields: {
withCredentials: true //跨域时带上cookies
},
type: "POST",
dataType: "json",
success: function (data) { console.log(data); }
});
Ext.Ajax.request({
url: 'http://localhost/CROS/Handler.ashx',
useDefaultXhrHeader: false, //设为false表示跨域请求
withCredentials: true, //跨域时带上cookies, 默认false不带cookies。后台要设置Access-Control-Allow-Credentials头为true
method: 'POST',
success:function(resp){
Ext.Msg.alert('success', resp.responseText);
},
failure:function(resp){
Ext.Msg.alert('failure', resp.responseText);
}
});
四、在Response中设置Header
这是针对单个请求(以Asp.Net为例)
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
#region 支持跨域请求
if (context.Request.Headers["Origin"] != null)
context.Response.AppendHeader("Access-Control-Allow-Origin", context.Request.Headers["Origin"]);
else
context.Response.AppendHeader("Access-Control-Allow-Origin", "*");
//context.Response.AppendHeader("Access-Control-Allow-Credentials", "true"); //如果前端请求有withCredentials: true, 则加上这句,表示允许请求带有Cookies信息,
//context.Response.AppendHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With");
//context.Response.AppendHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
#endregion
context.Response.ContentType = "application/json";
context.Response.Write("{a: 1, b: 2}");
}
}