Home >Web Front-end >JS Tutorial >How to Send JSON Data with jQuery\'s $.ajax Without Query String Conversion?
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 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.
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 });
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!