ajax跨域請求調用webservice接口

1.WebService 接口編寫web

步驟:新建web項目=》添加web service=》編寫方法接口=》而後發佈(本地測試能夠直接把這個web service運行起來)。ajax

關鍵如何讓外部Ajax 調用。json

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

 

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

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

(1)發佈時須要配置[WebService(Namespace = "http://192.168.1.90:5555/")]//這裏定義你發佈之後的域名地址。固然本地測試使用localhost就能夠或者使用默認的便可。測試

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

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

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調用。debug

$.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}code

相關文章
相關標籤/搜索