JSONP原理
- 判断请求与当前页面的域是否同源,
- 如果不同源,生成一个script标签,
- 随机生成一个callback名字,并创建一个名为这个的方法。callback=abc123456
- 设置script表签的src,设置为请求的接口
- 将callback作为参数拼接在后面
============以上是前端部分 - 后端接收到请求后,准备要返回的数据
- 后端拼接数据,将要返回的数据用callback的值和括号包裹起来。如:要返回的数据{“a”:1, “b”:2},将数据拼接为:abc123456({“a”:1, “b”:2})
- 将数据返回
============以上是后端部分 - 浏览器接收到内容,会当做JS代码执行
- 执行名为ABC23456的方法,这样就可以收到后端返回的数据
ajax: function(options) {
var url = options.url;
var type = options.type;
var dataType = options.dataType;
var targetProtocol = "";
var targetHost = "";
if (url.indexOf("http://") == 0 || url.indexOf("https://") == 0) {
var targetUrl = new URL(url);
targetProtocol = targetUrl.protocol;
targetHost = targetUrl.host;
} else {
targetProtocol = lacation.protocol;
targetHast = location.host;
}
if (dataType == "jsonp") {
if (lacation.protocol == targetProtocol && location.host == targetHost) {
} else {
var callback = cb + Math.floor(Math.random() * 10000);
window[callback] = options.success;
var script = document.creatElement("script");
if (url.indexOf("?") > 0) {
script.src = url + "&callback=" + callback;
} else {
script.src = url + "?callback=" + callback;
}
script.id = callback;
document.head.appendChild(script);
}
}
}