Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
67
rated 0 times [  69] [ 2]  / answers: 1 / hits: 15509  / 11 Years ago, wed, december 18, 2013, 12:00:00

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?


More From » http

 Answers
164

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.


[#73675] Tuesday, December 17, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
arron

Total Points: 663
Total Questions: 119
Total Answers: 112

Location: Belize
Member since Mon, Jun 20, 2022
2 Years ago
;