Rumah > hujung hadapan web > tutorial js > JSONP实现原理与案例详解

JSONP实现原理与案例详解

php中世界最好的语言
Lepaskan: 2018-04-25 15:46:50
asal
1524 orang telah melayarinya

这次给大家带来JSONP实现原理与案例详解,JSONP实现的注意事项有哪些,下面就是实战案例,一起来看一下。

跨域问题一直是前端中常见的问题,每当说到跨域,第一浮现的技术必然就是JSONP

JSONP在我的理解,它并不是ajax,它是在文档中插入一个script标签,创建_callback方法,通过服务器配合执行_callback方法,并传入一些参数

JSONP的局限就在于,因为是通过插入script标签,所以参数只能通过url传入,因此只能满足get请求,特别jQuery的ajax方法时,即使设置type: 'POST',但是只要设置了dataType: 'jsonp',在请求时,都会自动使用GET请求

实现逻辑

step1: 创建_callback方法 (_callback中可以删除script标签和_callback方法)

step2: 插入script标签

step3: 服务器输出js

实现:

var requestJsonp = function (opt) {
var funName, script;
/*
* step1 创建_callback方法
*/ 
//_callback函数名
funName = '_cb' + (Math.random() * 1000000);
//创建_callback方法
window[funName] = function (data) {
if (typeof opt.success == 'function') {
opt.success(data);
}
window[funName] = null;
delete window[funName];
document.body.removeChild(script);
script = null;
};
/*
* step2 插入script标签
*/
script = document.createElement('script');
script.type = 'text/javascript';
script.src = opt.url + (opt.url.indexOf('?') > -1 ? '&' : '?') + '_callback=' + funName;
document.body.appendChild(script);
/*
* step3 服务器输出js
* 服务器应接受url参数中_callback的值,作为函数名执行输出js
* 类似输出
* _callback({"name":"jsonp","description":"jsonp test"});
*/ 
/*
* 处理error
*/
script.addEventListener('error', function () {
window[funName] = null;
delete window[funName];
if (typeof opt.error == 'function') {
opt.error();
}
document.body.removeChild(script);
script = null;
});
};
requestJsonp({
url: 'http://www.url.org?tid=Jsx2',
success: function (data) {
console.log(data);
},
error: function () {
console.log('request error!');
}
});
Salin selepas log masuk

对于浏览器的行为就是插入script标签,执行js代码, 删除script标签

实现代码并没有考虑兼容以及传入data后生成url的问题。

下面给大家说下jsonp的优缺点:

JSONP的优点是:它不像XMLHttpRequest对象实现的Ajax请求那样受到同源策略的限制;它的兼容性更好,在更加古老的浏览器中都可以运行,不需要XMLHttpRequest或ActiveX的支持;并且在请求完毕后可以通过调用callback的方式回传结果。

JSONP的缺点则是:它只支持GET请求而不支持POST等其它类型的HTTP请求;它只支持跨域HTTP请求这种情况,不能解决不同域的两个页面之间如何进行JavaScript调用的问题。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

使用JSONP的案列归纳

在js中怎么把json当做参数使用

Atas ialah kandungan terperinci JSONP实现原理与案例详解. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan