How to transmit JSON data in Ajax?
To transfer JSON data format using AJAX, follow these steps:
- Instantiate an XMLHttpRequest object:
var xhttp = new XMLHttpRequest();
- Create a callback function to handle the server’s response.
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// 处理服务器的响应
}
};
- Open a connection to the server, specifying the method, URL, and whether it should be asynchronous.
xhttp.open("POST", "http://example.com/api", true);
- Set the request header to specify the data format as JSON.
xhttp.setRequestHeader("Content-Type", "application/json");
- 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.