Home >Web Front-end >JS Tutorial >How to Send JSON Data with jQuery\'s $.ajax Without Query String Conversion?

How to Send JSON Data with jQuery\'s $.ajax Without Query String Conversion?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-03 12:56:02452browse

How to Send JSON Data with jQuery's $.ajax Without Query String Conversion?

JSON Transmission in jQuery: Escaping the Query String Trap

When using jQuery's $.ajax function, it's common to encounter an unexpected behavior where data sent as JSON is automatically converted into a query string. This can be problematic if your application relies on receiving actual JSON objects.

The Misleading 'dataType: 'json'' Attribute

The first instinct is to set the 'dataType' attribute to 'json' to specify the expected data type. However, this only dictates the data type expected from the server, not what you send to it.

Solution: JSON.stringify and Content Type

To resolve this issue, you need to employ JSON.stringify to serialize your JavaScript object into a JSON string. Additionally, you must set the 'contentType' property to 'application/json' to instruct the server that the data being sent is JSON.

$.ajax({
    url: url,
    type: "POST",
    data: JSON.stringify(data),
    contentType: "application/json",
    complete: callback
});

Legacy Support

Modern browsers provide native JSON functionality. However, if legacy support is required, the json2 library can be used to emulate JSON behavior for older environments.

The above is the detailed content of How to Send JSON Data with jQuery's $.ajax Without Query String Conversion?. 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