ajax跨域請求調用webservice接口


1.WebService 接口編寫

步驟:新建web項目=》添加web service=》編寫方法接口=》然后發布(本地測試可以直接把這個web service運行起來)。

關鍵如何讓外部Ajax 調用。

首先,配置WebService 項目配置文件(web.config)紅色部分必須配置,這樣第三方才能調用接口方法(經測試通過,直接粘貼就ok),不懂可以百度。

 

<configuration>
    <system.web>
      <webServices> <protocols> <add name="HttpSoap"/> <add name="HttpPost"/> <add name="HttpGet"/> <add name="Documentation"/> </protocols> </webServices>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
  <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>
</configuration>

2、其次,這里貼出WebService 中代碼部分,這里我自定義一個返回一個Person集合GetPersonList(),可供Ajax調用。

(1)發布時需要配置[WebService(Namespace = "http://192.168.1.90:5555/")]//這里定義你發布以后的域名地址。當然本地測試使用localhost就可以或者使用默認的即可。

(2)要放開[System.Web.Script.Services.ScriptService] 的注釋。

以上兩步做到寫接口發布WebService,訪問http://192.168.1.90:5555/XXX.asmx 地址。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace MyWebService
{
    /// <summary>
    /// MyWebService 的摘要說明
    /// </summary>
    [WebService(Namespace = "http://localhost:47737/")] 
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允許使用 ASP.NET AJAX 從腳本中調用此 Web 服務,請取消注釋以下行。 
    [System.Web.Script.Services.ScriptService]
    public class MyWebService : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }

        [WebMethod]
        public int Add(int num1,int num2)
        {
            return num1 + num2;
        }
    }
}

3.第三方Ajax調用。

$.ajax({
                url: "http://localhost:47737/MyWebService.asmx/Add",
                type: "post",
                data: "{ 'num1': 2,'num2': 5 }",
                contentType: "application/json",
                dataType: "json",
                success: function (data) {
                    alert(data.d);
                },
                error: function () {
                    alert("發送ajax請求失敗!");
                }
            });

注意:這里data是響應的結果,使用data.d獲取數據,是因為返回來的數據格式為:{"d":7}


免責聲明!

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



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