将数据转换为JSON格式发送给API
代码示例:
// 创建XMLHttpRequest对象 var xhr = new XMLHttpRequest();
// 设置请求方法和url xhr.open('POST', 'https://api.example.com', true);
// 设置请求头为JSON格式 xhr.setRequestHeader('Content-Type', 'application/json');
// 将数据转换为JSON格式 var data = { name: 'John', age: 25 }; var jsonData = JSON.stringify(data);
// 发送请求 xhr.send(jsonData);
// 处理响应 xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { var response = JSON.parse(xhr.responseText); console.log(response); } };