[Phonegap+Sencha Touch] 移动开发49 js跨域请求的实现方法

如果是phonegap/cordova打包的,可以修改config.xml的access节点达到跨域的目的:
<access origin="*" />

如果是网站,可以有下面的实现方法:

一、使用代理
在你当前域中架设一个服务端B,通过这个服务端B去请求另一个域A。你的前台js请求服务端B


二、jsonp
这个大家都知道,实际上是将请求参数拼接到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>


jQuery代码:

$.ajax({ 
    url: "http://localhost/CROS/handler.ashx", 
    xhrFields: {
        withCredentials: true //跨域时带上cookies
    },
    type: "POST",
    dataType: "json",
    success: function (data) { console.log(data); }
}); 


ExtJs / Sencha Touch代码:

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);
    }
});


在II6中web.config不支持system.webServer配置节,所以需要在IIS中设置httprequestheader。

将web.config文件中的自定义头加入IIS的设置中。



四、在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}");
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

神秘_博士

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值