Home > Web Front-end > JS Tutorial > How to Send JSON Data Correctly with jQuery AJAX?

How to Send JSON Data Correctly with jQuery AJAX?

Linda Hamilton
Release: 2024-10-30 22:32:02
Original
808 people have browsed it

How to Send JSON Data Correctly with jQuery AJAX?

Sending JSON Data with jQuery

It's common to encounter this issue where data is transmitted in a query string like "&City=Moscow&Age=25" instead of a JSON format when using jQuery's AJAX function. This occurs because the necessary parameters for a JSON request have not been specified.

To resolve this, it's crucial to take the following steps:

  1. Convert the Data to JSON: Utilize the JSON.stringify method to convert the JavaScript object into a JSON string. Older browsers may require the inclusion of json2.js.
  2. Set the Content Type: Include the contentType property to specify the type of request being sent. In this case, use 'application/json; charset=utf-8'.
  3. Specify the Response Type: Indicate the expected response format from the server using the dataType property. Typically, it's best to set this to 'json'.

The corrected code below shows these modifications:

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);
    }
});
Copy after login

By following these steps, JSON data can be sent with jQuery AJAX correctly, ensuring data is transferred in the expected format.

The above is the detailed content of How to Send JSON Data Correctly with jQuery AJAX?. 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