1. 程式人生 > 其它 >ajax跨域請求呼叫

ajax跨域請求呼叫

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}

步驟:新建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}