简单配置IIS 以及web service 实现js跨域

因为浏览器的安全模型,js 是不能跨域的。

解决的方法有以下几种:

1. 使用代理服务转发

2. 目前服务器添加:Access-Control-Allow-Origin

3. 使用jsonp

4. 使用iframe

。。。。。。。

其中使用代理服务器进行转发以及 服务器添加Access-Control-Allow-Origin 是比较方便的。

代理服务器一般选择nginx 或者类似的,可以在网上找到对应的配置。

目的服务器添加Access-Control-Allow-Origin  对于现有的应用时比较方便的,直接在目的服务器中添加对应的信息即可。

例子如下:

public class App1 : System.Web.Services.WebService
{

[WebMethod]

public void HelloWorld()
{

Context.Response.ContentType = "application/json";
var text = "{\"name\":\"dalong\"}";
Context.Response.Write(text);

Context.Response.End();


}
}

web service 站点的配置如下:

<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />

<webServices >

<protocols >

<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>

</configuration>

IIS 服务器的配置如下:

Access-Control-Allow-Origin : *

对于 web service的方式可能会有其他的错误,需要在此添加以下信息:

Access-Control-Allow-Headers : Origin, X-Requested-With, Content-Type, Accept

上述配置也可以再 web.config 中配置

使用ajax 调用跨域的web  service 如下:

 $.ajax({
                type: "GET",    
                
                url: "http://XXXXXXXXXXX/app.asmx/HelloWorld",  
                data: null,
                dataType: 'json',
                success: function (result) {     
                    alert(result.name);
                }
            });   
 <system.webServer>
        <httpProtocol>
            <customHeaders>
                <add name="Access-Control-Allow-Origin" value="*" />
                <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
            </customHeaders>
        </httpProtocol>
    </system.webServer>

希望对大家有帮助。

 

 

 

 

posted on 2015-04-27 15:40  荣锋亮  阅读(854)  评论(0编辑  收藏  举报

导航