//jsonp的应用:
// $.ajax({
// url: “http://developer.duyiedu.com/edu/testJsonp”,
// type: “get”,
// dataType: “jsonp”,
// success: function(data) {
// console.log(data);
// }
// });
//jsonp的原理:
//1.判断请求与当前页面的域,是否同源,如果同源则发生正常的Ajax,就不跨域。
//2.如果不同源,生成一个script标签。
//3.生成一个随机的callback名字。
//4.设置script标签的src,设置为请求的接口。
//5.将callback作为参数拼接在后面。
//以上是前端部分
//6.后端收到请求后,开始准备要返回的数据。
//7.后端拼接数据,将要返回的数据用callback的值和括号包裹起来:例如 callback=asd123456,要返回的数据为{“a”:1, “b”:2},就要拼接为:asd123456({“a”:1},“b”:2);
//8.将内容返回。
//以上是后端部分
//9.浏览器收到内同,会当作js代码来执行。
//10.从而执行名为asd123456的方法。这样我们就接收到了后端返回给我们的对象。
var $ = {
ajax: function(options) {
var url = options.url;
var type = options.type;
var dataType = options.dataType;
//判断是否同源
//获取目标url的域
var targetProtocol = ""; //目标接口协议
var targetHost = ""; //目标接口的host,host是包含域名和端口的
//如果url不带http,那么访问的一定是相对路径,相对路径一定是同源的
if (url.indexOf("http://") == 0 || url.indexOf("https://") == 0) {
var targetUrl = new URL(url);
targetProtocol = targetUrl.protocol;
targetHost = targetUrl.host;
} else {
targetProtocol = location.protocol;
targetHost = location.host;
}
//首先判断是否为jsop,因为不是jsonp不用做其他的判断,直接发送ajax
if (dataType == 'jsonp') {
if (location.protocol == targetProtocol && location.host == targetHost) {
//因为同源,jsonp会当作普通的Ajax做请求
} else {
//随机生成一个callback
var callback = "cb" + Math.floor(Math.random() * 1000000);
//给window添加一个方法
window[callback] = options.success;
console.log(window[callback]);
//生产script标签
var script = document.createElement("script");
if (url.indexOf("?") > 0) {
//表示已经有参数了
script.src = url + "&callback=" + callback;
} else {
//表示没有参数
script.src = url + "?callback" + callback;
}
console.log(callback);
script.id = callback;
document.head.appendChild(script);
}
}
}
}
$.ajax({
url: "http://developer.duyiedu.com/edu/testJsonp",
type: "get",
dataType: "jsonp",
success: function(data) {
console.log(data);
}
});