Ajax:服务器相应的数据格式

服务器响应的数据格式

在真实的项目中服务器大多数情况下会以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>

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值