AJAX请求服务端响应JSON数据
在实际工作中向服务端发送请求,返回的结果绝大多数都是json格式的数据。
案例:
在窗口下按下键盘任意按键,便会向服务端发送一个请求,服务端返回结果在div中呈现。
前端页面
<style>
#result{
width: 200px;
height: 100px;
border: solid 1px #b;
}
</style>
<body>
<div id="result"></div>
<script>
const result=document.getElementById('result');
window.onkeydown=function(){
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;
}
}
}
}
</script>
</body>
服务端文件 server.js
const express=require('express');
const app=express();
app.all('/json-server',(request,response)=>{
response.setHeader('Access-Control-Allow-Origin','*');
response.send('HELLO AJAX JSON');
});
app.listen(8000,()=>{
console.log("服务已经启动...");
})
启动服务后,进入页面进行测试
由此得知确实是在
response.send('HELLO AJAX JSON');
得到响应
我们的实际目标是要相应一个数据,并非是得到响应体。
const data={
name:'zhanghan'
};
let str=JSON.stringify(data);
response.send(str);
再此特别提醒,我们的data对象不能直接放到send()中去响应,因为send()所接收的是一个字符串,因此我们需要对data对象进行数据类型的转换。
由图可知,我们的得到的是一个JSON的字符串,为了提取里面的数据,我们通常有两种方法。
1.手动转化
let data = JSON.parse(xhr.response);
console.log(data);
result.innerHTML=data.name;
结果:
2.自动转换
xhr.responseType='json';
console.log(xhr.response);
result.innerHTML=xhr.response.name;
结果: