jquery+ajax跨域請求webservice

來源:互聯網
上載者:User

標籤:style   blog   http   color   java   os   使用   io   檔案   

最近幾天在學習webservice。。。在學習的時候便想到用ajax的方式去請求webservice。。

一直在測試。。如果這個被請求的webservice和自己使用的是同一個連接埠號碼。則不用考慮那ajax跨域的問題。。

由於ajax沒有許可權跨域訪問。。也就是說。。不是一個連接埠號碼沒法用。。我是這麼理解的。。

現在可以通過一個jsonp來實現ajax跨域的問題。其本質還是通過script標籤動態載入js。

首先。我建立一個網站。。再建立一個WebService.asmx檔案

該檔案寫了三個方法

其中這兩個方法是供後台調用。。。直接return結果就行了。。

///     /// 無任何參數    ///     ///     [WebMethod]    public string HelloWorld()    {        return "Hello World";    }    /// <summary>    /// 一個參數    /// </summary>    /// <param name="name">參數名</param>    /// <returns></returns>    [WebMethod]    public string Hello(string name)    {        return string.Format("Hello {0}", name);    }

這個方法是返回給ajax的。。大夥應該知道ajax處理資料的格式是json。。所以在這裡寫的是json格式。。

[WebMethod]    public void GetLoginId(string loginId)    {        //在請求的URL加參數jsoncallback=?,注意這裡jsoncallback=?是關鍵所在!其中?符號會被JQuery自動替換成其它的回調方法名稱,        //我們關心的是jsoncallback=?起什麼作用了?原來jsoncallback=?被替換後,會把方法名稱傳給伺服器。        //我們在伺服器端要做什麼工作呢?伺服器要接受參數jsoncallback,然後把jsoncallback的值作為JSON資料方法名稱返回。        //因此HttpContext.Current.Request["jsoncallback"]中這個參數名稱必須是jsoncallback。。        string callback = HttpContext.Current.Request["jsoncallback"];        HttpContext.Current.Response.Write(callback +            "({result:\"true\"})");         //關於result這詞是你自己自訂的屬性         //會作為回調參數的屬性供你調用結果        HttpContext.Current.Response.End();    }

那麼。我這個WebService檔案的內容就是這樣的

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Services;/// <summary>///WebService 的摘要說明/// </summary>[WebService(Namespace = "http://tempuri.org/")][WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]//若要允許使用 ASP.NET AJAX 從指令碼中調用此 Web 服務,請取消對下行的注釋。 // [System.Web.Script.Services.ScriptService]public class WebService : System.Web.Services.WebService {    public WebService () {        //如果使用設計的組件,請取消注釋以下行         //InitializeComponent();     }    ///     /// 無任何參數    ///     ///     [WebMethod]    public string HelloWorld()    {        return "Hello World";    }    /// <summary>    /// 一個參數    /// </summary>    /// <param name="name">參數名</param>    /// <returns></returns>    [WebMethod]    public string Hello(string name)    {        return string.Format("Hello {0}", name);    }    [WebMethod]    public void GetLoginId(string loginId)    {        //在請求的URL加參數jsoncallback=?,注意這裡jsoncallback=?是關鍵所在!其中?符號會被JQuery自動替換成其它的回調方法名稱,        //我們關心的是jsoncallback=?起什麼作用了?原來jsoncallback=?被替換後,會把方法名稱傳給伺服器。        //我們在伺服器端要做什麼工作呢?伺服器要接受參數jsoncallback,然後把jsoncallback的值作為JSON資料方法名稱返回。        //因此HttpContext.Current.Request["jsoncallback"]中這個參數名稱必須是jsoncallback。。        string callback = HttpContext.Current.Request["jsoncallback"];        HttpContext.Current.Response.Write(callback +            "({result:\"true\"})");         //關於result這詞是你自己自訂的屬性         //會作為回調參數的屬性供你調用結果        HttpContext.Current.Response.End();    }    }

這樣之後還沒有完。。

因為WebService預設不支援Get請求,所以要在Web.config設定檔內的<system.web>節點內添加以下這段元素:

<system.web><webServices>        <protocols>          <add name="HttpGet"/>          <add name="HttpPost"/>        </protocols></webServices></system.web>

這是加在服務端的web.config中。。

這個webservice啟動並執行

現在就開始請求這個webservice。。

建立一個工程。。引入這個服務

請求這個服務的aspx檔案

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="WebDemo.index" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">    <title></title>    <script src="Scripts/jquery-1.7.1.js" type="text/javascript"></script>     <script type="text/javascript">        //Document載入完畢後初始化方法//        $(function Init() {//                        $("#TxtLoginId").bind("blur", CkLoginId);//            //CkLoginId();//        });        //帳號驗證及提示        function CkLoginId() {            var Id = $("#TxtLoginId").val();            alert(Id);            $.ajax({                url: "http://localhost:61390/WebSite1/WebService.asmx/GetLoginId?jsoncallback=?",                dataType: "jsonp",                data: { "loginId": Id },                success: OnSuccess,                error: OnError            });        }        function OnSuccess(json) {            alert(json.result);        }        function OnError(XMLHttpRequest, textStatus, errorThrown) {            targetDiv = $("#data");            if (errorThrown || textStatus == "error" || textStatus == "parsererror" || textStatus == "notmodified") {                targetDiv.replaceWith("請求資料時發生錯誤!");                return;            }            if (textStatus == "timeout") {                targetDiv.replaceWith("請求資料逾時!");                return;            }        }      </script></head><body>    <form id="form1" runat="server">    <table border="0" cellspacing="0" cellpadding="0" width="100%">        <tr>            <td>                <asp:Label ID="LblLoginId" runat="server" Text="帳&nbsp;&nbsp;號" ClientIDMode="Static"></asp:Label>                <asp:TextBox ID="TxtLoginId" runat="server" ClientIDMode="Static"></asp:TextBox>                <button id="login" onclick="CkLoginId()">登陸</button>            </td>        </tr>    </table>    </form></body></html>

如果按照我這樣寫的話。。。貌似只能用ie測試才會彈出true框。。其他瀏覽器不行。。我也不知道這到底是什麼原因。。

但是如果把下面這個方法取消注釋。

        $(function Init() {                        $("#TxtLoginId").bind("blur", CkLoginId);            //CkLoginId();        });

那麼不管用什麼瀏覽器測試都可以正常彈出true框。。

下面是取消上邊那個初始化函數的注釋之後的。。

後台請求服務的代碼

ServiceReference.WebServiceSoapClient tt = new ServiceReference.WebServiceSoapClient();            Response.Write(tt.HelloWorld());

那麼這樣就成功了。。。我說的不太詳細。。可以參考下面兩個網址。。可能說的比較詳細清楚。。我也才學。。嘿嘿。。就一個菜鳥。。

學習自:http://www.cnblogs.com/VAllen/archive/2012/07/12/JQueryAjaxRegion.html#3015100

    http://www.cnblogs.com/wupeiqi/archive/2013/03/07/2949014.html

jquery+ajax跨域請求webservice

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.