[AJAX]原生AJAX——服务端如何发出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>

</body>
<script>
    // 1、创建对象
    const xhr = new XMLHttpRequest();
    // 2、初始化:设置请求类型和url
    xhr.open('POST', 'http://127.0.0.1:8000/server');

    // 设置请求头
    // Content-Type:设置请求体内容类型
    // application/x-www-form-urlencoded:请求参数的类型
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    // 3、发送:设置请求体(POST请求的参数)
    xhr.send("id:1&name:CUYG")
    // 4、事件绑定
    xhr.onreadystatechange = function () {
        // 判断
        if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
                console.log(xhr.response);
            }
        }
    };
</script>

</html>

主要代码

// 第一步:设置发给客户端的JSON格式数据

    var data={

        code:200,

        msg:"成功"

    }

    // 第二步:由于response.send()只能发送字符串,所以要把JSON转换成字符串

    data = JSON.stringify(data)

    // 第三步:发送数据

    response.send(data);

根据上图表示客户端接收到数据,打印出的响应参数是字符串

 方法一:使用JSON.parse(xhr.response)把字符串转换为JSON

<script>
    // 1、创建对象
    const xhr = new XMLHttpRequest();
    // 2、初始化:设置请求类型和url
    xhr.open('POST', 'http://127.0.0.1:8000/server');
    // 设置请求头
    // Content-Type:设置请求体内容类型
    // application/x-www-form-urlencoded:请求参数的类型
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    // 3、发送:设置请求体(POST请求的参数)
    xhr.send("id:1&name:CUYG")
    // 4、事件绑定
    xhr.onreadystatechange = function () {
        // 判断
        if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
                console.log(JSON.parse(xhr.response));
            }
        }
    };
</script>

方法二:设置响应体数据类型:xhr.responseType="json"

<script>
    // 1、创建对象
    const xhr = new XMLHttpRequest();
    // 2、初始化:设置请求类型和url
    xhr.open('POST', 'http://127.0.0.1:8000/server');

    // 设置请求头
    // Content-Type:设置请求体内容类型
    // application/x-www-form-urlencoded:请求参数的类型
    xhr.responseType="json"
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    // 3、发送:设置请求体(POST请求的参数)
    xhr.send("id:1&name:CUYG")
    // 4、事件绑定
    xhr.onreadystatechange = function () {
        // 判断
        if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
                console.log(xhr.response);
            }
        }
    };
</script>

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值