我们请求后端的时候一般返回的是字符串,而我们需要的数据,因此我们在请求到JSON数据的时候需要对他们进行转换。

手动转换

借助JSON的parse方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//发送请求
const xhr = new XMLHttpRequest();
//初始化
xhr.open('GET', 'http://127.0.0.1:8000/json-server');
//发送
xhr.send();
//事件绑定
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
//
// console.log(xhr.response);
// result.innerHTML = xhr.response;

// 1. 手动对数据转化
let data = JSON.parse(xhr.response); //-----------------------------
console.log(data);
result.innerHTML = data.name;

}
}
}

自动转换

借助xhr对象上的一个属性来进行设置。

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
//发送请求
const xhr = new XMLHttpRequest();

//设置响应体数据的类型
xhr.responseType = 'json'; //----------------------------------------

//初始化
xhr.open('GET', 'http://127.0.0.1:8000/json-server');
//发送
xhr.send();
//事件绑定
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
//
// console.log(xhr.response);
// result.innerHTML = xhr.response;
// 1. 手动对数据转化
//let data = JSON.parse(xhr.response);
//console.log(data);
//result.innerHTML = data.name;

// // 2. 自动转换
console.log(xhr.response);
result.innerHTML = xhr.response.name;
}
}
}