Ajax的同源政策与跨域请求

同源政策

Ajax只能向自己的服务器发送请求。A网站中的HTML文件只能向A网站服务器中发送Ajax请求,A网站是不能向B网站发送Ajax请求的。

使用JSONP解决同源限制问题

jasonp = json with padding
不属于ajax请求,但是可以模拟Ajax请求。

利用script标签发送请求
解决的是get请求,传递参数需要拼接url

封装

客户端(浏览器端)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function jsonp(options) {
// 动态创建script标签
var script = document.createElement('script');
// 拼接字符串的变量
var params = '';
for(var attr in options.data) {
params += '&' + attr + '=' options.data[attr];
}
var fnName = 'myJsonp' + Math.random().toString().replace('.', '');
// 将它变成全局函数
window[fnName] = options.success;
// 为script标签添加src属性
script.src = options.url + '?callback=' + fnName + params;
// 将script标签追加到页面中
document.body.appendChild(script);
// 为script标签添加onload事件
script.onload = function() {
document.body.removeChild(script);
}
}

服务器端

💡 阅读更多
Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×