我环顾四周并按照this post上的说明操作,但我仍然无法执行错误功能.我想要做的是让我的PHP脚本返回错误或成功以及消息.最终它将是从数据库返回的数据,将被放入div中,但是现在我只需要让错误处理工作.我希望有人可以帮助我解决这个问题.我在下面提供了我的代码.
这显然是我的AJAX请求.
function getProductInfo() {
if($("#serialNumber").val() != '') {
serialNumber = $("#serialNumber").serialize();
$.ajax({
type: "POST",
url: 'post.PHP',
data: serialNumber + "&getSerialNumber=" + 1,
dataType: 'json',
success: function(data, textStatus, jqXHR) {
console.log("SUCCESS");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("ERROR");
}
});
}
}
function getSerialNumber() {
$serial = $_POST['serial'];
$product = new Inventory;
if($product->GetSerial($serial)) {
$productInfo = $product->GetSerial($serial)->first();
echo '{"error": false, "message": "Successfully got serial number"}';
} else {
echo '{"error": true, "message": "Failed to get serial number"}';
}
}
作为当前的代码,只要它确实有错误,它将只保持输出SUCCESS.
解决方法:
您需要发送200以外的http状态代码:
if($product->GetSerial($serial)) {
$productInfo = $product->GetSerial($serial)->first();
header('Content-Type: application/json', true, 200);
die(json_encode(["error"=> false, "message"=> "Successfully got serial number"]));
} else {
header('Content-Type: application/json', true, 400);
die(json_encode(["error"=> true, "message"=> "Failed to get serial number"]));
}
另外,在发送json时,相应地设置内容类型,并且永远不要尝试手动构建json字符串,而是使用内置的json_encode函数,并且最好使用die()或exit()而不是echo,以避免任何意外的额外输出
也就是说,虽然发送适当的状态代码似乎是一个好主意,但您可能会发现总是返回200并解析响应更容易,并保留错误处理程序以应对意外错误
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。