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

×