zoukankan      html  css  js  c++  java
  • 简单配置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>

    希望对大家有帮助。

     

  • 相关阅读:
    PV、UV、VV、IP是什么意思?
    多用户远程linux
    实用性阅读指南读书笔记
    在VS添加万能头文件 操作
    sqrt函数实现之卡马克方法
    大端法、小端法及其判断方法
    STL源码剖析之ROUND_UP函数实现原理及其拓展
    海康和多益面经
    小米实习生面试面经
    阿里c++一面面经
  • 原文地址:https://www.cnblogs.com/rongfengliang/p/4460373.html
Copyright © 2011-2022 走看看