Home > Web Front-end > JS Tutorial > body text

jquery ajax中使用jsonp的限制解决方法_jquery

WBOY
Release: 2016-05-16 17:13:08
Original
1078 people have browsed it

jsonp 解决的是跨域 ajax 调用的问题。为什么要跨域 ajax 调用呢?这样可以在一个应用中直接在前端通过 js 调用另外一个应用(在不同的域名下)的 API。
我们在实际应用中也用到了 jsonp ,但之前只知道 jsonp 的一个限制,只能发 get 请求,get 请求的弊端是请求长度有限制。
今天,发现 jsonp 的另外一个限制(在jquery ajax的场景下) —— 不会触发 $.ajax 的error callback,示例代码如下:

复制代码 代码如下:

$.ajax({
    dataType: 'jsonp',           
    error: function (xhr) {
        //出错时不会执行这个回调函数
    }
});

这个限制由 jsonp 的实现机制决定。

解决方法:

使用一个 jquery 插件 —— jquery-jsonp,https://github.com/jaubourg/jquery-jsonp

示例代码:

复制代码 代码如下:


复制代码 代码如下:

$.jsonp({
    url: '',
    success: function (data) {
    },
    error: function (xOptions, textStatus) {
        console.log(textStatus);
    }
});

当 jsonp 请求出错时,比如 404 错误,error 回调函数会执行,输出字符串"error"。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!