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状态码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<script>
var xhr = new XMLHttpRequest();
// 0 已经创建了Ajax对象,但是还没有对Ajax对象进行配置
console.log(xhr.readyState);
xhr.open('get', 'http://localhost:3000/readystate');
// 1 已经对Ajax对象进行配置,但是还没有发送请求
console.log(xhr.readyState);

// 当Ajax状态码发生变化的时候触发
xhr.onreadystatechange = function() {
// 2 请求已经发送了
// 3 已经接收到服务器端的部分数据了
// 4 服务器短的响应数据已经接收完成
console.log(xhr.readyState);

//如果状态码的值为4就代表数据已经接收完成了
if(xhr.readyState == 4)
{
console.log(xhr.resposeText);
}
}

// 时间监听函数要卸载send()之前

xhr.send();


</script>

获取服务器端的响应

两种获取方式的区别

区别描述 onload事件 onreadystatechange事件
是否兼容IE低版本 不兼容 兼容
是否需要判断Ajax状态码 不需要 需要
被调用次数 一次 多次

推荐使用onload

IE低版本浏览器缓存问题

两次请求相同的地址时,第二次请求并不会真正发送出去,而是直接从缓存中取上一次的响应结果。

解决方法:在发送请求的地址上用?拼接一个随机参数,使得每次请求的地址不相同。

Ajax封装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
function ajax(options) {

// 存储默认值
var defaults = {
type: 'get',
url: '',
data: {},
header: {'Content-Type': 'application/x-www-form-urlencoded'},
success: function () {},
error: function () {}
}

Object.assign(defatuls, options);

// 创建Ajax对象
var xhr = new XMLHttpRequest();
var params = '';
for(var attr in defaults.data) {
params += attr + '=' + defaults.data[attr] + '&';
}
// 截取掉最后的&符号
params = params.substr(0, params.length - 1);

// 判断请求方式
if(defaults.type == 'get') {
defaults.url = defaults.url + '?' + params;
}
// 配置Ajax对象
xhr.open(defaults.type, defaults.url);
// 如果请求方式为post
if(defaults.type == 'post') {
// 用户希望的向服务器端传递的请求参数的类型
var contentType = defaults.header['Content-Type'];
// 设置请求参数格式的类型
xhr.setRequsetHeader('Content-Type', contentType);
if(contentType == 'application/json'){
xhr.send(JSON.stringify(defaults.data));
}
else {
xhr.send(params);
}
}else {
// 发送请求
xhr.send();
}

// 监听xhr对象下面的onload事件
// 当xhr对象接受完响应数据后触发
xhr.onload = function() {
// 当http状态码等于200的时候
if(xhr.status == 200) {
// 请求成功 调用处理
defaults.success(xhr.responseText, xhr);
} else {
defaults.error(xhr.responseText, xhr);
}
}
}

ajax({
// 请求方式
type: 'get',
// 请求地址
url: 'http://localhost:3000/first',
data: {
name: 'zhangsan',
age: 20,
},
header: {
'Content-Type': 'application/x-www-form-urlencoded',
},
success: function(data, xhr) {
console.log(data);
},
error: function(data, xhr) {
console.log(data);
}
})

作者

Jhuoer Yen

发布于

2021-10-12

更新于

2023-09-18

许可协议

评论

Your browser is out-of-date!

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

×