【问题标题】:XMLHttpRequest - How to trap situation where an HTML error page is returned instead of dataXMLHttpRequest - 如何捕获返回 HTML 错误页面而不是数据的情况
【发布时间】:2013-02-20 12:03:26
【问题描述】:

Javascript:使用 XMLHttpRequest 获取少量数据,这些数据由网络服务器上的特定 php 例程回显给它。与回调函数异步。或同步,没有任何可能性。

如果 php 文件不存在或无法访问,则会出现问题。 responseText 属性不返回错误标志,而是返回服务器 404 错误页面的 HTML 内容。

404 页面内容会因服务器而异,因此几乎不可能通过任何字符串测试来捕获这种情况。有什么方法可以标记发生错误的事实并返回 null 吗?

 // envvars is set previously
 AjaxRequest.open('post','handler.php?nocache='+nocache,true);
 AjaxRequest.setRequestHeader("User-Agent",'Firefox');
 AjaxRequest.onreadystatechange = aCallback;
 AjaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 AjaxRequest.setRequestHeader("Content-length", envvars.length);
 AjaxRequest.setRequestHeader("Connection", "close");
 AjaxRequest.send(envvars);
}

function aCallback() {
 if(AjaxRequest.readyState == 4){
   var response = AjaxRequest.responseText;
   if(response == 0){
     // It is useless to test for failure here because a complete 404 page is returned, 
     // instead of a null or -1 response. 
     document.ajax.response.value="Fail";   
    } else {
     document.ajax.response.value=response;   
   }
 }
}

// handler.php:
if ($_POST["request"]=="countbananas"):
  echo "bananas=43" ;
endif;

ps 我知道会提到 jQuery,但我宁愿避开这条路线。

【问题讨论】:

  • 检测不到HTTP状态码是404吗?
  • 认为我找到了答案。如果正常,AjaxRequest.status 属性将为 200。看起来编写我的代码所基于的示例的人不知道如何正确捕获错误。花了一段时间才发现这个属性存在,很少有例子提到它。无论如何谢谢。

标签: javascript xmlhttprequest http-status-code-404


【解决方案1】:

不能使用 XMLHttpRequest 返回的HTTP status code 吗?

if ( AjaxRequest.status + "" == "404" ) {
  // Error page
}

或者:

// 4xx status code
if ( (AjaxRequest.status + "").substr(0,1) == "4" ) {
  // Error page
}

【讨论】:

  • 是的,谢谢,我们发现我使用的示例错误处理方法不正确。这是正确的方法。
【解决方案2】:

你可以读取status property of the XMLHttpRequest对象来获取HTTP响应码:

function aCallback() {
 if(AjaxRequest.readyState == 4){
   if(AjaxRequest.status !== 200){
     // something went wrong
     document.ajax.response.value="Fail";   
    } else {
     var response = AjaxRequest.responseText;
     document.ajax.response.value=response;   
   }
 }
}

这当然假设您的源返回正确的 HTTP 代码,例如“404 文件未找到”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-24
    • 2018-08-27
    • 2021-06-02
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多