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);
}
}

服务器端

💡 阅读更多

Ajax请求的学习与尝试

Ajax 学习笔记

这几天在学习 node.js,看到 Ajax 的部分内容比较零散,很难记忆,但是 Ajax 又是相当重要的知识,实际开发中也常常会用到,所以写个笔记来整理一下。


请求参数的格式

在请求头中指定 Content-Type 属性的值

1. application/x-www-form-urlencoded

name=zhangsan&age=20&sex=男

2. application/json

{name: 'zhangsan', age: '20', sex: '男'}

注意:get 请求是不能提交 json 对象数据格式的,传统网站的表单提交也是不支持 json 对象数据格式的。

Ajax 状态码

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

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

×