php - 在 ajax 请求回调中显示 PHP 错误
问题描述
在一个页面中test.php
,我只是激活了错误报告,我停用了日志记录,然后我调用了一个test()
不存在的函数。正如预期的那样,如果我运行代码,我会收到错误消息:
(!) Fatal error: Uncaught Error: Call to undefined function test() in [path-to]/test.php on line 7 (!) Error: Call to undefined function test() in [path-to]/test.php on line 7 Call Stack # Time Memory Function Location 1 0.1336 355848 {main}( ) .../test.php:0
现在,在另一个页面中index.php
,我只有一个按钮 - 名为testButton
. 如果我按下它,则会执行对页面的 ajax 请求test.php
。在index.php
我期望看到:
- 抛出的错误由ajax请求
test.php
的回调处理;error
- 错误显示在屏幕上。
不幸的是,这一切都没有发生。当我按下按钮时:
- ajax请求的
success
回调被调用; - 屏幕上不显示错误。
你能帮我找到问题,或者找出错误吗?
谢谢你。
使用系统:
- PHP:7.1.1
- 阿帕奇版本:2.2.31
- Apache API 版本:20051115
- jQuery:3.3.1
测试.php:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 0);
$data = test();
索引.php:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Test: Displaying Errors</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#testButton').click(function (event) {
$.ajax({
method: 'post',
dataType: 'html',
url: 'test.php',
data: {},
success: function (response, textStatus, jqXHR) {
$('#result').html('Successful test... Unfortunately :-)');
},
error: function (jqXHR, textStatus, errorThrown) {
/*
* When an HTTP error occurs, errorThrown receives the textual portion of
* the HTTP status, such as "Not Found" or "Internal Server Error". This
* portion of the HTTP status is also called "reason phrase".
*/
var message = errorThrown;
/*
* If a response text exists, then set it as message,
* instead of the textual portion of the HTTP status.
*/
if (jqXHR.responseText !== null && jqXHR.responseText !== 'undefined' && jqXHR.responseText !== '') {
message = jqXHR.responseText;
}
$('#result').html(message);
}
});
});
});
</script>
</head>
<body>
<h3>
Test: Displaying Errors
</h3>
<div id="result">
Hier comes the test result. Since an error is thrown, I expect it to appear hear.
</div>
<br/>
<form method="post" action="">
<button type="button" id="testButton" name="testButton">
Start the test
</button>
</form>
</body>
</html>
解决方案
jQuery AJAX 调用中的success
anderror
函数只是检查请求的 HTTP 状态代码。当 PHP 产生错误时,它不会更改状态代码,因此 jQuery 会触发该success
函数。如果要使用 jQuery 错误,则必须更改状态代码。您可以通过捕获Error
(PHP >= 7) 来做到这一点:
try {
$data = test();
}
catch (\Error $e) {
http_response_code(500);
echo $e->getMessage();
}
或者您可以将状态代码保留为200
(默认)并以 JSON 格式发送您的响应,包括您喜欢的成功和错误属性,以及您可能希望随请求返回的任何其他内容。
header('Content-type: application/json');
$response['success'] = true;
$response['error'] = null;
try {
$data = test();
}
catch (\Error $e) {
$response['success'] = false;
$response['error'] = $e->getMessage();
}
echo json_encode($response);
并确保dataType
从 ajax 请求中删除该属性,以让 jQuery 自动确定类型标头。
如果您的程序意外抛出错误,这可能意味着您做错了什么。如果您希望它抛出错误,则需要捕获它们。这要么意味着将事物包装在 try/catch 块中,要么是 , 的组合set_exception_handler()
,set_error_handler()
并register_shutdown_function()
在全局范围内完成此任务。
推荐阅读
- javascript - 如何用新的另一个字符串和 javascript 中的填充替换字符串的前 5 个字符?
- javascript - 我无法阻止函数执行
- c# - 将数据表的行附加到 Excel 并在 C# 上跳过 Excel 上的某些列
- node.js - fs readFileSync 方法可能引发哪些错误?
- aws-glue - 强制 AWS Glue 爬虫创建多个表
- javascript - Nodejs 在使用 Promise 时阻塞代码。为什么?
- c# - 如何在 ASP.NET Core 3 上通过 IoC 从 FluentValidation 启用 CascadeMode.Stop?
- java - 我可以更改工具栏“主页”图标的大小和位置吗?
- php - 如何将 php 代码中的结果转换为 html 页面
- javascript - JavaScript 交换单选按钮的输入值