服务器响应的数据格式
在真实的项目中服务器大多数情况下会以JSON对象作为响应数据的格式。当客户端拿到响应数据时,要将JSON数据和HTML字符串进行拼接,然后将拼接的结果使用DOM操作的方式追加到页面中。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 1.创建ajax对象
var xhr = new XMLHttpRequest();
xhr.open('get','http://localhost:3000/responseData');
// 发送请求
xhr.send();
xhr.onload = function(){
console.log(xhr.responseText)
console.log(typeof xhr.responseText)
}
</script>
</body>
</html>
// 引入express框架
const express = require('express');
const path = require('path');
// 创建网站的服务器
const app = express();
// 静态资源访问服务功能
app.use(express.static(path.join(__dirname,'public')));
app.get('/first',(req,res) => {
// send()
// 1.send()方法内部会检测响应内容的类型
// 2.send方法会帮我们自动检测HTTP状态码
// 3.send方法会帮我们设置响应内容的类型以及编码
res.send('Hello,Ajax');
});
app.get('/responseData',(req,res) => {
res.send({"name":"xinxin"});
});
// 监听端口
app.listen(3000);
console.log('网站服务器启动成功');
在http请求与响应的过程中,无论是请求参数还是响应内容,如果是对象类型,最终都会被转换为对象字符串进行传输
JSON.parse()//将json字符串转换为json对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 1.创建ajax对象
var xhr = new XMLHttpRequest();
xhr.open('get','http://localhost:3000/responseData');
// 发送请求
xhr.send();
xhr.onload = function(){
// console.log(typeof xhr.responseText)
var responseText = JSON.parse(xhr.responseText)
// console.log(xhr.responseText)
// console.log(typeof xhr.responseText)
console.log(responseText)
var str = '<h2>'+ responseText.name +'</h2>'
document.body.innerHTML = str;
}
</script>
</body>
</html>