Home > Article > Web Front-end > Why is my jQuery AJAX request sending data as plain text instead of JSON?
In web development, it's often crucial to transmit data efficiently between the client-side and the server. jQuery, a popular JavaScript library, offers convenient methods for handling such data exchange. One common task is sending data in JSON format to the server using jQuery.
However, sometimes developers encounter an issue where data is not transmitted in the desired JSON format but as plain text. To understand why this occurs, let's examine a code snippet:
var arr = {City:'Moscow', Age:25}; $.ajax( { url: "Ajax.ashx", type: "POST", data: arr, dataType: 'json', async: false, success: function(msg) { alert(msg); } } );
This code attempts to send the data in the arr object to the Ajax.ashx server using the $.ajax method. However, the issue arises because the code does not specify the request content type or correctly construct the JSON request.
To rectify this, the JSON.stringify method should be used to convert the JavaScript object into a native JSON string:
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); } });
Key Points to Note:
Additional Considerations:
The above is the detailed content of Why is my jQuery AJAX request sending data as plain text instead of JSON?. For more information, please follow other related articles on the PHP Chinese website!