js怎么把json数组发送出去
时间: 2023-05-18 22:07:30 浏览: 67
你可以使用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数组的字符串表示。