Home > Web Front-end > JS Tutorial > body text

How to Send JSON Data Directly with jQuery\'s $.ajax?

DDD
Release: 2024-11-01 06:01:02
Original
706 people have browsed it

How to Send JSON Data Directly with jQuery's $.ajax?

How to Transmit JSON Directly via $.ajax Rather Than a Query String

When working with jQuery's $.ajax method, you may encounter an issue where it automatically converts JSON data into a query string. To prevent this conversion and transmit actual JSON, follow these simple steps:

  1. Serialize Your Object to JSON: Use the JSON.stringify method to convert your object into a JSON string. This ensures that your data remains in JSON format.
  2. Set Content Type: Specify the Content-Type header as "application/json" in your $.ajax request. This informs the server that the data being sent is in JSON format.

Here's an updated code snippet that implements both steps:

<code class="javascript">$.ajax({
    url: url,
    type: "POST",
    data: JSON.stringify(data),
    contentType: "application/json",
    complete: callback
});</code>
Copy after login

Additional Notes:

  • JSON.stringify is natively available in browsers supporting JavaScript 1.7 / ECMAScript 5 or later.
  • If you need support for legacy browsers, you can utilize the json2 library.
  • By following these steps, you can ensure that your JSON data is sent directly to the server without any unintended conversions.

The above is the detailed content of How to Send JSON Data Directly with jQuery\'s $.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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!