JS,XMLHttpRequest,Post发送Json格式,接收Json格式

首次发布:2024-12-16
1
2
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
// 创建XMLHttpRequest对象实例
var xhr = new XMLHttpRequest();
// 准备要发送的JSON数据
var data = {
    name: "John",
    age: 30,
    hobbies: ["reading""swimming"]
};
// 将JSON对象转换为字符串
var jsonData = JSON.stringify(data);
 
// 配置请求,使用POST方法,设置请求头告知服务器发送的是JSON数据
xhr.open('POST''https://xx.luofenming.com/api/data'true);
xhr.setRequestHeader('Content-Type''application/json');
 
// 注册事件监听器,当请求状态改变时触发
xhr.onreadystatechange = function () {
        //readyState等于 4(表示请求已完成)且status等于 200(表示请求成功)
    if (xhr.readyState === 4 && xhr.status === 200) {
        // 解析接收到的JSON格式响应数据
        var responseData = JSON.parse(xhr.responseText);
        console.log(responseData);
    }
};
 
// 发送请求,传入JSON格式的字符串数据
xhr.send(jsonData);

本文来自 www.LuoFenMing.com