jquery ajax中使用jsonp的限制(转)

http://www.cnblogs.com/dudu/archive/2012/12/04/jquery_ajax_jsonp.html

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

解决方法:

使用一个 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 on 2013-11-04 22:23  ※WYF※  阅读(343)  评论(0编辑  收藏  举报