用XMLHttpRequest发送和接收JSON数据

百度的AI回答了一个案例:

var xhr = new XMLHttpRequest();
var url = "your_endpoint_url"; // 替换为你的API端点
var data = JSON.stringify({
  key1: "value1",
  key2: "value2"
});
 
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    // 请求成功
    var response = JSON.parse(xhr.responseText);
    console.log(response);
  }
};
 
xhr.send(data);

我觉得已经回答得不错的了,这里要注意两点:

1.xhr.setRequestHeader("Content-Type", "application/json");不可缺少;

2.xhr.send(data);的时候,里面这个data,必须是字符串的,所以上面用JSON.stringify()转成了字符串来传输到后端。

参考:

JS使用XMLHttpRequest对象POST收发JSON格式数据

要使用CORS(跨域资源共享)发送JSON数据接收JSON数据,需要在服务端设置允许跨域访问,然后在前端使用XMLHttpRequest(XHR)对象或Fetch API发送请求。 以下是使用XHR对象发送JSON数据接收JSON数据的示例代码: ```javascript const xhr = new XMLHttpRequest(); const url = 'https://example.com/api/data'; const data = { name: 'John', age: 30 }; xhr.open('POST', url, true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onreadystatechange = function() { if(xhr.readyState === 4 && xhr.status === 200) { const responseData = JSON.parse(xhr.responseText); console.log(responseData); } }; xhr.send(JSON.stringify(data)); ``` 在这个例子中,我们使用XHR对象向https://example.com/api/data发送一个POST请求,并发送JSON数据。我们设置请求头Content-Type为application/json,告诉服务端我们发送的是JSON数据。我们还使用JSON.stringify方法将JavaScript对象转换为JSON字符串。在响应中,我们使用JSON.parse方法将JSON字符串转换为JavaScript对象并打印输出。 Fetch API也可以用来发送CORS请求并接收JSON数据,示例代码如下: ```javascript const url = 'https://example.com/api/data'; const data = { name: 'John', age: 30 }; fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(responseData => console.log(responseData)) .catch(error => console.error(error)); ``` 在这个例子中,我们使用Fetch API向https://example.com/api/data发送一个POST请求,并发送JSON数据。我们设置请求头Content-Type为application/json,告诉服务端我们发送的是JSON数据。我们还使用JSON.stringify方法将JavaScript对象转换为JSON字符串。在响应中,我们使用response.json()方法将响应体转换为JavaScript对象并打印输出。在这个例子中,我们还使用了Promise来处理响应。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值