
我们请求后端的时候一般返回的是字符串,而我们需要的数据,因此我们在请求到JSON数据的时候需要对他们进行转换。
手动转换
借助JSON的parse方法。
| 12
 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) {
 
 
 
 
 
 let data = JSON.parse(xhr.response);
 console.log(data);
 result.innerHTML = data.name;
 
 }
 }
 }
 
 | 
自动转换
借助xhr对象上的一个属性来进行设置。
| 12
 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.name;
 }
 }
 }
 
 | 
AJAX 手动和自动将请求的JSON数据进行字符串转换