简体   繁体   中英

Is it necessary to pass request data as JSON string to server

When making an AJAX request to a server (may be Java, PHP, etc), is it necessary to pass data as JSON string ?

Can we not pass the object directly ? Are there issues de-serializing OR can that be handled at the backend ? Any examples of handling JS object (if it is possible to send an obj directly) at the backend would be great ?

Object literal makes sense only in the JavaScript runtime environment. Since AJAX body is simply a string, you can pass {a:3} to a server. But what should server side do with it? It ertainly can store it in a database and return to you back when requested. But what if it wanted to extract some data from it? You' have to have JS runtime and evaluate the object using eval . Which would be awkward, but possible. However, not all servers have JS runtime environment. Whereas there are libraries for many languages that support parsing JSON into the representation specific to the language on the server.

An AJAX request passes data to the server in the same way any other HTTP request does. Most commonly, AJAX requests use POST and pass data to the server as POST data, but query strings are often used, and there are other ways to pass data to a server using HTTP and AJAX.

In essence all HTTP data is octets (bytes), and HTTP has no special support for serialization of JavaScript objects, so you or the libraries and/or frameworks you use must handle the serialization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM