繁体   English   中英

收听 Ajax 呼叫的 500 个响应?

[英]Listen for 500 responses on Ajax calls?

我正在收听网页上的 xhr 事件,以捕捉任何可能的请求失败。 为了听所有这些,我正在应用这个伪猴子补丁:

var reqOpen = XMLHttpRequest.prototype.open;

XMLHttpRequest.prototype.open = function() {
this.addEventListener('load', function() {

console.log(this.readyState); // this is always 4, but I'm trying to 
listen for when it's not successful
console.log(this.responseText); //the respoinse

});

reqOpen.apply(this, arguments);

它在成功响应时起作用,但除此之外它不会捕获任何东西。

有什么方法可以尝试捕获不成功的请求(特别是返回 500 响应的请求?

谢谢

load事件仅在请求成功完成时触发。 onreadystatechange事件将在请求过程中的每一步触发。

在该事件处理程序中,检查4readyState ,这意味着请求已完成,无论成功与否。 然后检测status属性是否为500 此属性将是您要查找的 HTTP 响应代码。

不会有有效负载,因为服务器无法发回响应,从而使responseText无用。 而是检查statusText属性以获取与 HTTP 状态相对应的消息。

var reqOpen = XMLHttpRequest.prototype.open;

XMLHttpRequest.prototype.open = function() {
  this.addEventListener('readystatechange', function() {
    if (this.readyState === 4 && this.status === 500) {
      console.log(this.statusText);
    }
  });

  reqOpen.apply(this, arguments);
}

您可以在load事件或loadend事件中访问status

此演示中使用的端点返回 500

 var reqOpen = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function() { this.addEventListener('loadend', function() { if(this.status > 200){ console.log('Loadend Status:', this.status) } }); this.addEventListener('load', function() { console.log('Load Status:', this.status) }); reqOpen.apply(this, arguments); } // example making request with jQuery ajax that uses XMLHTtpRequest $.get('https://httpstat.us/500')
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM