jquery ajax中使用jsonp的限制

來源:互聯網
上載者:User

jsonp 解決的是跨域 ajax 調用的問題。為什麼要跨域 ajax 調用呢?這樣可以在一個應用中直接在前端通過 js 調用另外一個應用(在不同的網域名稱下)的 API。

我們在實際應用中也用到了 jsonp ,但之前只知道 jsonp 的一個限制,只能發 get 請求,get 請求的弊端是請求長度有限制。

今天,發現 jsonp 的另外一個限制(在jquery ajax的情境下) —— 不會觸發 $.ajax 的error callback,範例程式碼如下:

$.ajax({    dataType: 'jsonp',                error: function (xhr) {        //出錯時不會執行這個回呼函數    }});

這個限制由 jsonp 的實現機制決定。

網上找到兩篇資料談到這個問題:

[jQuery] .ajax() with dataType: 'jsonp' will not use error callback if request fails

JSONP error handling with jquery.ajax

更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/webkf/ajax/

解決方案:

使用一個 jquery 外掛程式 —— jquery-jsonp,https://github.com/jaubourg/jquery-jsonp

範例程式碼:

<script src="https://raw.github.com/jaubourg/jquery-jsonp/master/src/jquery.jsonp.js"></script>
$.jsonp({    url: '',    success: function (data) {    },    error: function (xOptions, textStatus) {        console.log(textStatus);    }});

當 jsonp 請求出錯時,比如 404 錯誤,error 回呼函數會執行,輸出字串"error"。

相關文章

聯繫我們

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