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

×