"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Posted on 2025-03-24
Browse:948

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:

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);
    }
});

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."
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3