简体   繁体   English

为什么500错误打破了ajax调用?

[英]Why does 500 error break ajax call?

This is my code: 这是我的代码:

http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) http_request.overrideMimeType('text/javascript');
http_request.onreadystatechange = alertContents;
http_request.open('POST', base_url, true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", parameters.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(parameters);

Being run in the latest firefox. 在最新的Firefox中运行。

This code normally works perfectly, but when the page called produces a 500 internal server error javascript stops running on the page, and further events scheduled with setInterval/setInterval do not get executed. 此代码通常可以正常工作,但是当调用的页面产生500内部服务器错误时,javascript停止在页面上运行,并且使用setInterval / setInterval调度的其他事件不会被执行。 Why does this happen? 为什么会这样? How do I catch it? 我怎么抓住它?

The problem may be in your alertContents function (not shown in your question). 问题可能在您的alertContents函数中(未在您的问题中显示)。 A function called by .onreadystatechange almost always looks something like this: .onreadystatechange调用的函数几乎总是看起来像这样:

var callback = function() {
  if (http_request.readyState==4 && http_request.status==200) {
    // do stuff
  }
}

if the page produces a 500 Http code then the if statement will fail and the rest of the code in the callback will not execute. 如果页面产生500 Http代码,则if语句将失败,并且回调中的其余代码将不会执行。 To catch it add: 要抓住它,请添加:

else if(http_request.readyState==4 && http_request.status==500) {
  console.log('The server\'s on fire!');
}

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

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