Home  >  Article  >  Web Front-end  >  How to Send JSON Data with jQuery: Avoiding Form-Encoded Strings?

How to Send JSON Data with jQuery: Avoiding Form-Encoded Strings?

DDD
DDDOriginal
2024-11-04 09:02:30828browse

How to Send JSON Data with jQuery: Avoiding Form-Encoded Strings?

Send JSON Data with jQuery: Avoiding Form-Encoded Strings

While using jQuery's $.ajax() to transmit JSON data, developers may encounter issues where the data is sent as form-encoded strings instead of the intended JSON format. This occurs when certain parameters are omitted.

Consider the following code:

var arr = {City:'Moscow', Age:25};
$.ajax(
   {
        url: "Ajax.ashx",
        type: "POST",
        data: arr,
        dataType: 'json',
        async: false,
        success: function(msg) {
            alert(msg);
        }
    }
);

In this code, the data is being sent as form-encoded strings (e.g., "City=Moscow&Age=25") rather than JSON. To resolve this issue, two crucial steps must be taken:

  1. Convert Data to JSON Format:
    Use the JSON.stringify() method to convert the JavaScript object (arr) into a JSON string.

    var arr = { City: 'Moscow', Age: 25 };
    var json_data = JSON.stringify(arr);
  2. Specify Request Content Type:
    Set the contentType property to 'application/json; charset=utf-8' to indicate that the request contains JSON data.

    contentType: 'application/json; charset=utf-8',

The corrected code below incorporates these changes:

$.ajax({
    url: 'Ajax.ashx',
    type: 'POST',
    data: json_data,
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    async: false,
    success: function(msg) {
        alert(msg);
    }
});

These adjustments ensure that the data is sent as JSON, allowing the server to correctly process the request and return the desired JSON response.

The above is the detailed content of How to Send JSON Data with jQuery: Avoiding Form-Encoded Strings?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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