JS跨域ajax訪問


方式1:jsonp解決跨域訪問

需要服務和js配合

服務

[WebMethod]
        public void HelloWorld2(string name)
        {
            HttpContext.Current.Response.ContentType = "application/json;charset=utf-8";
            string jsonCallBackFunName = string.Empty;
            jsonCallBackFunName = HttpContext.Current.Request.Params["jsoncallback"].ToString();
            HttpContext.Current.Response.Write(jsonCallBackFunName + "({ \"Result\": \"Helloword2" + name + "\" })");
        }

JS調用

 var dataStr = "name=" + $("#birthday").val();
                $.ajax({
                    type: "post",
                    url: "http://192.168.0.99:8082/WebService1.asmx/HelloWorld",
                    dataType: "jsonp",
                    jsonp: 'jsoncallback',
                    contentType: "application/jsonp;charset=utf-8",
                    data: dataStr,
                    success: function (result) {
                        //返回結果
                        alert(result.Result);
                        $("#name").val(result.Result);
                    },
                    error: function (e) {
                        window.alert(e.status);
                    }
                });
            });

方式2:增加配置處理跨域

如果是在.net下則在web.config中增加配置

在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>

如果是調用webservice在服務端config中增加配置在system.web下增加

<protocols>
        <add name="HttpSoap"/>
        <add name="HttpPost"/>
        <add name="HttpGet"/>
        <add name="Documentation"/>
</protocols>

服務

 [WebMethod]
        public string HelloWorld1(string name)
        {
            return "{data:你好:" + name + "}";
        }

前台調用方式

$.ajax({
                    type: "post",
                    url: "http://192.168.0.99:8082/WebService1.asmx/HelloWorld",
                    dataType: "json",
                    data: "{name:'" + birthday + "'}",//參數
                    contentType: "application/json;charset=utf-8",
                    success: function (result) {
                        //返回結果  
                        $("#name").val(result.d);
                    },
                    error: function (e) {
                        window.alert(e.status);
                    }
                });
            });


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM