jquery ajax中使用jsonp的限制

jsonp 解决的是跨域 ajax 调用的问题。为什么要跨域 ajax 调用呢?这样可以在一个应用中直接在前端通过 js 调用另外一个应用(在不同的域名下)的 API。

如果你对 JSONP 不太了解,推荐阅读【原创】说说JSON和JSONP,也许你会豁然开朗,含jQuery用例

我们在实际应用中也用到了 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

解决方法:

使用一个 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"。 

posted @ 2012-12-04 16:09  dudu  阅读(7702)  评论(5编辑  收藏  举报