How to retrieve the AJAX response status code?

After making a request using AJAX, you can use the status property of the XMLHttpRequest object to retrieve the response status code. The response status code indicates the server’s handling result of the request, common status codes include 200 for success, 404 for resource not found, and 500 for internal server error.

Below is an example of using AJAX to retrieve response status codes:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api', true);
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) {
    var status = xhr.status;
    console.log(status); // 输出响应状态码
  }
};
xhr.send();

In the above example, we can retrieve the response status code with xhr.status and output it to the console. The xhr.readyState indicates the current state of the request, with a value of 4 signifying that the request is complete. Therefore, it is only valid to get xhr.status when xhr.readyState is 4.

广告
Closing in 10 seconds
bannerAds