JS-JQuery(JSONP)調用WebService跨域若干技術點

來源:互聯網
上載者:User

標籤:style   blog   c   java   tar   ext   

 

1、JSONP:JSON With Padding,讓網頁從別的網域擷取資訊,也就是跨域擷取資訊,可以當做是一種“工具”,大多數架構Jquery、EXTjs等都支援。

  由於同源策略,一般來說位於 server1.example.com 的網頁無法與不是 server1.example.com的伺服器溝通,而 HTML 的<script> 元素是一個例外。利用 <script> 元素的這個開放策略,網頁可以得到從其他來源動態產生的 JSON 資料,而這種使用模式就是所謂的 JSONP。用 JSONP 抓到的資料並不是 JSON,而是任意的JavaScript,用 JavaScript 直譯器執行而不是用 JSON 解析器解析。

2、WebService,這裡使用VS2010內建,不使用WCF。

       說明:jsoncallback是針對前台網頁的函式宣告,不要問web服務方法為什麼這個樣寫,目的是為了跨域調用需要;此方法發布到IIS後直接調用是執行不了,會出現【HttpContext.Current.Request.Params["jsoncallback"].ToString()】這句代碼出錯返回NullReferenceException。

[WebMethod]

        public   void GetSingleInfo(string   x, string y)

        {

            HttpContext.Current.Response.ContentType   = "application/json;charset=utf-8";

            string   jsonCallBackFunName = HttpContext.Current.Request.Params["jsoncallback"].ToString();

//上面代碼必須

//中間代碼執行自己的業務操作,可返回自己的任意資訊(多資料類型)

            GetAttrData   gad = new GetAttrData();

            string   result = gad.GetSingleInfo(x, y);

//下面代碼必須

            HttpContext.Current.Response.Write(string.Format("{0}({1})",   jsonCallBackFunName, result));

            HttpContext.Current.Response.End();

        }

 

3、WebService的Web.config配置,是服務端,和Web服務一起。

       Protocols聲明網頁Get/Post方式,務必要增加這個節點,在system.web節點內。

<system.web>

              <!-- 。。。其他節點 -->

    <webServices>

      <protocols>

        <add name="HttpPost"/>

        <add name="HttpGet"/>

      </protocols>

    </webServices>

  </system.web>

 

4、用戶端網頁(aspx,asp,jsp,html)跨域調用——Jquery為例

<!—頭部引用 -->

    <script type="text/javascript" src="/js/jquery-1.4.4.js"></script>

    <!-- 解決jquery和其他引入的JS的$存在衝突,可選

    <script   type="text/javascript">var JQ=$;</script>

    -->

<!—在功能執行JS調用Web服務的函數內   -->

    JQ.ajax({

             type: "get",

             url: "http://10.0.0.29/TheDimDataService/GetDataString.asmx/GetSingleInfo?jsoncallback=?",

             dataType: "jsonp",

             jsonp: "jsoncallback",

             data: {x:xv,y:yv},  //傳輸的資料

             success: function (result){},  //得到調用服務結果

                       error:OnError 

    });

 

  參考

  [1] JSONP之百度百科

  另WCF Ajax、Jquery跨域訪問點開見此。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.