본문 바로가기
TIL/TIL

JSON, JSON.stringify, ajax

by koreashowme 2020. 1. 22.

when sending json via ajax do you need to turn it into a string to send it?

If it isn't a string, then it isn't JSON in the first place.

JSON is a text based data format. HTTP is a text based communications protocol.

JSON stands for javascript object notation

JSON is based on the syntax for JavaScript literals. A JavaScript object is not JSON.

 

 

AJAX is all about HTTP requests, which are basically "text" requests to a server. That's the main reason why you have to stringify your object: That way it's turned into text that can "travel" over HTTP.

 

 

When sending data to a web server, the data has to be a string.

That's why we are using JSON.stringify() function to convert data to string and send it via XHR request to the server.

 

// Creating a XHR object let xhr = new XMLHttpRequest();

let url = "submit.php";

 

// open a connection

xhr.open("POST", url, true);

 

// Set the request header i.e. which type of content you are sending

xhr.setRequestHeader("Content-Type", "application/json");

 

// Converting JSON data to string

var data = JSON.stringify({ "name": name.value, "email": email.value });

 

// Sending data with the request

xhr.send(data);

 

https://stackoverflow.com/questions/32570523/why-when-sending-data-over-ajax-do-you-have-to-json-stringify-your-objects/59845736#59845736

'TIL > TIL' 카테고리의 다른 글

JSON, JSON.parse(), JSON.STRINGIFY ( DELETE )  (0) 2020.01.22
JSON, JSON.parse(), JSON.STRINGIFY ( POST )예제  (0) 2020.01.22
배열 method  (0) 2020.01.22
Array(5).join(" " + object.key);  (0) 2020.01.21
Array Method  (0) 2020.01.21

comment