处理AJAX调用导致的PHP致命错误


Handling a fatal error in PHP from an AJAX call

很简单,我希望我的javascript能够对PHP导致的致命500错误做出适当的反应。

我的目标仅仅是收集脚本产生的致命错误消息,这样我就可以在客户端显示它。

这有可能吗?

编辑:清理了问题,以防它被偶然搜索到。

处理PHP致命错误:

register_shutdown_function("foo");
function foo() {
  $e = error_get_last();
  if($e & (E_ERROR | E_COMPILE_ERROR | E_CORE_ERROR)) //all fatal errors
    [handle the error. I turn the error into a json encoded object that is parsed by JS]
}

通过检查所有致命错误,您将不会触发先前发生的通知或警告句柄,但不会停止脚本的执行。希望你已经处理过了。

注:

使用jQuery处理致命错误:
$(document).ajaxError( function(e, xhr, settings, exception) {
  [handle 500 error. xhr.responseText will contain the printed text.]
});
$.post( [...] );

详情见http://api.jquery.com/ajaxError/

最后注意:如果你想解析JSON, 显示错误应该关闭,否则文本将出现在JSON编码的对象之前。

查看.status是否有AJAX请求

ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function()
{
  if(ajaxRequest.readyState == 4 && ajaxRequest.status == 500)
  {
    //do something
  }
}
ajaxRequest.open("GET","path/file.php?var=variable");
ajaxRequest.send();

总而言之

我将此代码提供给另一个用户,这将是您在这里的解决方案。只需使用Jquery 1.5 XHR对象来接收错误状态,如果是错误状态,则从javascript代码中使用它:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
$(function(){
    alert('getting page');
    jqXHR = $.get(
        'index.php', 
        function(data){
            alert(data);
        }
    )
    .success(function(){ alert('second success'); })
    .error(function(){ alert('error'); })
    .complete(function(){ alert('complete'); });
});
</script>