Home > Web Front-end > JS Tutorial > Detailed explanation of JSONP principles and case analysis

Detailed explanation of JSONP principles and case analysis

php中世界最好的语言
Release: 2018-04-25 09:32:53
Original
1945 people have browsed it

This time I will bring you a detailed explanation of the JSONP principle and case analysis. What are the precautions for the detailed explanation of the JSONP principle and case analysis. The following is a practical case, let's take a look.

In the web2.0 era, proficient use of ajax is a necessary skill for every front-end siege engineer. However, due to browser restrictions, Ajax does not allow cross-domain communication.

JSONP is the current mainstream solution for cross-domain communication.

Although in jquery, we can call jsonp by setting the dataType of $.ajax to jsonp, there is no relationship between the implementation principles of jsonp and ajax. jsonp mainly uses script to link to remote URLs to implement cross-domain requests. For example:

<script src="http://jsonp.js?callback=xxx"></script>
Copy after login

callback defines a function name, and the remote server transfers parameters by calling the specified function and passing in the parameters.

I have searched many articles on the Internet. Their implementation methods are too simple and require more modifications for practical application. I have encapsulated an object here that can be directly used in actual operations.

var JSONP = {
// 获取当前时间戳
now: function() {
return (new Date()).getTime();
},
// 获取16位随机数
rand: function() {
return Math.random().toString().substr(2);
},
// 删除节点元素
removeElem: function(elem) {
var parent = elem.parentNode;
if(parent && parent.nodeType !== 11) {
parent.removeChild(elem);
}
},
// url组装
parseData: function(data) {
var ret = "";
if(typeof data === "string") {
ret = data;
}
else if(typeof data === "object") {
for(var key in data) {
ret += "&" + key + "=" + encodeURIComponent(data[key]);
}
}
// 加个时间戳,防止缓存
ret += "&_time=" + this.now();
ret = ret.substr(1);
return ret;
},
getJSON: function(url, data, func) {
// 函数名称
var name;
// 拼装url
url = url + (url.indexOf("?") === -1 ? "?" : "&") + this.parseData(data);
// 检测callback的函数名是否已经定义
var match = /callback=(\w+)/.exec(url);
if(match && match[1]) {
name = match[1];
} else {
// 如果未定义函数名的话随机成一个函数名
// 随机生成的函数名通过时间戳拼16位随机数的方式,重名的概率基本为0
// 如:jsonp_1355750852040_8260732076596469
name = "jsonp_" + this.now() + '_' + this.rand();
// 把callback中的?替换成函数名
url = url.replace("callback=?", "callback="+name);
// 处理?被encode的情况
url = url.replace("callback=%3F", "callback="+name);
}
// 创建一个script元素
var script = document.createElement("script");
script.type = "text/javascript";
// 设置要远程的url
script.src = url;
// 设置id,为了后面可以删除这个元素
script.id = "id_" + name;
// 把传进来的函数重新组装,并把它设置为全局函数,远程就是调用这个函数
window[name] = function(json) {
// 执行这个函数后,要销毁这个函数
window[name] = undefined;
// 获取这个script的元素
var elem = document.getElementById("id_" + name);
// 删除head里面插入的script,这三步都是为了不影响污染整个DOM啊
JSONP.removeElem(elem);
// 执行传入的的函数
func(json);
};
// 在head里面插入script元素
var head = document.getElementsByTagName("head");
if(head && head[0]) {
head[0].appendChild(script);
}
}
};
Copy after login

The implementation process is basically written in the comments, you can read it yourself. The calling method is basically the same as jQuery. For example:

var data = {
from: "北京",
count: 27,
output: "json",
callback: "?"
}
JSONP.getJSON("http://api.qunar.com/cdnWebservices.jcp", data, function(json) {console.log(json)});
Copy after login

Of course, you can write it like this:

JSONP.getJSON("http://api.qunar.com/cdnWebservices.jcp?from=北京&count=27&output=json&callback=?", null, function(json) {console.log(json)});
Copy after login

As for the implementation of the server, it is relatively simple. Take PHP as an example:

$callback = !empty($_GET['callback']) ? $_GET['callback'] : 'callback';
echo $callback.'( .json_encode( $data ).')';
Copy after login

Some additional explanations on the similarities and differences between ajax and jsonp:

1. The two technologies of ajax and jsonp "look" very similar in terms of calling methods and have the same purpose. It requests a URL and then processes the data returned by the server. Therefore, frameworks such as jquery and ext encapsulate jsonp as a form of ajax;

2. However, ajax and jsonp are essentially different. s things. The core of ajax is to obtain non-this page content through XmlHttpRequest, while the core of jsonp is to dynamically add the

Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template