How to transmit JSON data in Ajax?

To transfer JSON data format using AJAX, follow these steps:

  1. Instantiate an XMLHttpRequest object:
var xhttp = new XMLHttpRequest();
  1. Create a callback function to handle the server’s response.
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    // 处理服务器的响应
  }
};
  1. Open a connection to the server, specifying the method, URL, and whether it should be asynchronous.
xhttp.open("POST", "http://example.com/api", true);
  1. Set the request header to specify the data format as JSON.
xhttp.setRequestHeader("Content-Type", "application/json");
  1. Convert the data to a JSON string and send it to the server.
var data = { "name": "John", "age": 30 };
xhttp.send(JSON.stringify(data));

On the server side, you can use relevant programming languages (such as Java, Python, etc.) to parse the received JSON data.

bannerAds