How to request JSON data with Ajax?
The general steps for requesting JSON data using AJAX are as follows:
- Use the $.ajax function
- Specify the request method and URL. Normally, use the GET method to fetch JSON data, where the URL is the address of the server-side resource containing the JSON data.
- Set the request header to indicate that the content type is JSON.
- when the state changes
- xhr.on ready state change is equal to a function that…
- The value of xhr.readyState is equal to 4.
- The value of xhr.status is equal to 200.
- Submit the request.
Here is an example code using native AJAX to request JSON data:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'data.json', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
// 在这里处理响应的JSON数据
}
};
xhr.send();
In the above code, the request method and URL are set by calling xhr.open method. Next, the request header is set using xhr.setRequestHeader method. Then, a callback function to handle the JSON response data is set using xhr.onreadystatechange. Finally, the request is sent by calling xhr.send() method.
Please note that the URL in the example above is a relative path with respect to the current page. You can replace it with the actual URL you are using.