js把json发送出去
时间: 2023-05-19 22:02:49 浏览: 38
可以使用XMLHttpRequest对象或fetch API将JSON数据发送到服务器。例如,使用fetch API可以这样发送JSON数据:
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
相关问题
js怎么把json发送出去
可以使用XMLHttpRequest对象或fetch API将JSON数据发送到服务器。使用XMLHttpRequest对象时,可以使用send()方法将JSON数据作为参数发送。使用fetch API时,可以使用POST方法并将JSON数据作为请求体发送。以下是使用XMLHttpRequest对象发送JSON数据的示例代码:
```
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://example.com/api');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
console.log('JSON data sent successfully');
} else {
console.log('Error sending JSON data');
}
};
xhr.send(JSON.stringify({key1: 'value1', key2: 'value2'}));
```
使用fetch API发送JSON数据的示例代码如下:
```
fetch('http://example.com/api', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({key1: 'value1', key2: 'value2'})
})
.then(function(response) {
if (response.ok) {
console.log('JSON data sent successfully');
} else {
console.log('Error sending JSON data');
}
})
.catch(function(error) {
console.log('Error sending JSON data:', error);
});
```
js怎么把json数组发送出去
你可以使用XMLHttpRequest对象或fetch API来发送JSON数组。首先,将JSON数组转换为字符串,然后将其作为请求体发送。以下是一个使用XMLHttpRequest对象发送JSON数组的示例代码:
```
var data = [{name: "John", age: 30}, {name: "Jane", age: 25}];
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://example.com/api");
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify(data));
```
这将发送一个POST请求到"http://example.com/api",请求体为JSON数组的字符串表示。
如果你使用fetch API,代码将类似于以下示例:
```
var data = [{name: "John", age: 30}, {name: "Jane", age: 25}];
fetch("http://example.com/api", {
method: "POST",
headers: {
"Content-Type": "application/json;charset=UTF-8"
},
body: JSON.stringify(data)
});
```
这将发送一个POST请求到"http://example.com/api",请求体为JSON数组的字符串表示。