jquery ajax中使用jsonp的限制

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

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"。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值