使用jsonp實現ajax跨域請求

來源:互聯網
上載者:User

標籤:des   style   blog   http   java   color   使用   os   

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

JSONP的優點是:

它不像XMLHttpRequest對象實現的Ajax請求那樣受到同源策略的限制;它的相容性更好,在更加古老的瀏覽器中都 可以運行,不需要XMLHttpRequest或ActiveX的支援;並且在請求完畢後可以通過調用callback的方式回傳結果。 

 

JSONP的缺點則是:

它只支援GET請求而不支援POST等其它類型的HTTP請求;它只支援跨域HTTP請求這種情況,不能解決不同域的兩個頁面之間如何進行JavaScript調用的問題。

JSONP是一種指令碼注入(Script Injection)行為,有一定的安全隱患。

 

下面說說如何?:

 

一、首先需要在你的webservice的web.config中system.web節點裡加入以下節點:

<webServices>      <protocols>        <add name="HttpPost"/>        <add name="HttpGet"/>      </protocols>    </webServices>

 

二、webservice代碼,為了同時支援一般的請求與jsonp ajax請求,代碼如下:

using System.Web.Services;using System.Collections.Generic;using System.Data;using System.Web;/// <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{    /// <summary>    /// 在ajax請求返回後,會自動將這些類型轉換為json對象    /// </summary>    public WebService()    {    }    [WebMethod(Description = "測試")]    public string getInfos(string infostring)    {        string result = infostring;//所要返回的json資料        string jsonCallBackFunName = HttpContext.Current.Request.Params["jsoncallback"] + "";        if (string.IsNullOrEmpty(jsonCallBackFunName))        {            HttpContext.Current.Response.ContentType = "application/json;charset=utf-8";            HttpContext.Current.Response.Write(jsonCallBackFunName + "(" + infostring + ")");            HttpContext.Current.Response.End();        }        return result;    }}

 

三、頁面及js代碼:

<!DOCTYPE html><html><head>    <title>Index</title>    <script src="jquery-1.8.3.js" type="text/javascript"></script>    <script type="text/javascript">        $(function () {            $("#tj").click(function () {                var dataStr = "info=ABCTest";                $.ajax({                    type: "get",                    url: http://xxx/jQueryMobile.asmx/getInfos?jsoncallback,                    dataType: "jsonp",                    jsonp: ‘jsoncallback‘,                    data: dataStr,                    success: function (result) {                        alert(result.xxx);                    }                });            });        });    </script></head><body>    <div>        <input id="tj" type="button" value="提交" />    </div></body></html> 

 

 

如果遇到類似:Error... parsererror jQuery15001997238997904205_1298484897373 was not called

說明是解析出問題了,我一開始也碰到了,這個很有可能是你服務端返回的json格式有問題,或者拼接出問題了。

聯繫我們

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