在JavaScript中发送JSON数据通常涉及到使用XMLHttpRequest
对象或者更现代的fetch
API。以下是两种常见的方法来发送JSON数据:
XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open("POST", 'https://example.com/api', true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
var data = {
name: "John",
age: 30
};
xhr.send(JSON.stringify(data));
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
console.log(response);
}
};
fetch
APIvar data = {
name: "John",
age: 30
};
fetch('https://example.com/api', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => console.log(data))
.catch((error) => {
console.error('Error:', error);
});
application/json
。Content-Type
为application/json
的请求,并且能够解析JSON格式的数据。如果你遇到了具体的问题,可以提供更详细的信息,以便给出更具体的解决方案。
领取专属 10元无门槛券
手把手带您无忧上云