Home > Web Front-end > JS Tutorial > How to Send JSON Data with jQuery: Why Am I Receiving a Query String Instead?

How to Send JSON Data with jQuery: Why Am I Receiving a Query String Instead?

Susan Sarandon
Release: 2024-11-02 10:30:30
Original
266 people have browsed it

How to Send JSON Data with jQuery: Why Am I Receiving a Query String Instead?

Understanding JSON Data Transmission with jQuery

Sending data in JSON format is crucial for efficient communication between web pages and servers. However, if you encounter data being sent in an unformatted manner, like "City=Moscow&Age=25," it may be due to the lack of proper request configuration.

The provided code attempts to send JSON data using jQuery's $.ajax() method. By default, jQuery converts data to a query string, resulting in the "City=Moscow&Age=25" format. To resolve this, follow these steps:

  1. Use JSON.stringify(): Convert the JavaScript object (arr) into a JSON string using JSON.stringify().
  2. Set Request Content Type: Specify the request content type as "application/json; charset=utf-8" using the contentType property. This informs the server that the data is being sent as JSON.
  3. Ensure JSON Response: Set the dataType: 'json' property to indicate that the expected response from the server should be in JSON format.

Here is the corrected code:

<code class="javascript">var arr = { City: 'Moscow', Age: 25 };
$.ajax({
    url: 'Ajax.ashx',
    type: 'POST',
    data: JSON.stringify(arr),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    async: false,
    success: function(msg) {
        alert(msg);
    }
});</code>
Copy after login

Additional Notes:

  • arr is not an array but a JavaScript object. Arrays are enclosed in [].
  • The success callback will automatically parse the JSON response into a JavaScript object if the server respects HTTP protocol and responds with "Content-Type: application/json."

The above is the detailed content of How to Send JSON Data with jQuery: Why Am I Receiving a Query String Instead?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template