问题
Normal, we can send an Ajax request or submit a form to a server, which in the HTTP request body would be encoded like this: name=helloworld&age=123
.
Now our server only accepts JSON data as the request body. Is there a way to change the encoding method of the request body in JavaScript?
回答1:
HTML forms give you three options for encoding the data. text/plain
is useful only for debugging (and not very useful even when given browser developer tools), and neither of the other two are JSON.
With XHR, the encoding is however you encode the data.
The send method can take a string: You can encode the data in that string however you like.
function sendJSON() {
var data = {
name: "helloworld",
age: 123
};
var json = JSON.stringify(data);
var xhr = new XMLHttpRequest();
xhr.open("POST", "/example/");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(json);
}
You can also pass other kinds of data such as a FormData object (which can include files and will us multipart encoding) but you don't need anything so complex for JSON.
来源:https://stackoverflow.com/questions/20661363/javascript-how-can-i-post-an-arbitrary-request-body-to-a-server