如何让jQuery ajax执行错误功能
I have looked around and followed the instructions on this post but I still can not get the error
function to execute. What I want to do is have my PHP script return either error
or success
along with a message. Eventually it will be data returned from a database that will be put inside of a div
but for now I just need to get the error handling working. I am hoping someone here can help me out with this. I have included my code below.
我环顾四周并按照这篇文章的说明进行操作,但仍然无法执行错误功能。我想要做的是让我的PHP脚本返回错误或成功以及消息。最终它将是从数据库返回的数据,将被放入div中,但是现在我只需要让错误处理工作。我希望有人可以帮助我解决这个问题。我在下面提供了我的代码。
This is obviously my AJAX request.
这显然是我的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");
}
});
}
}
This is my php function that will return the error and message as JSON
这是我的php函数,它将以JSON的形式返回错误和消息
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"}';
}
}
As the current code stand it will only keep outputting SUCCESS
regardless if it actually has an error or not.
就目前的代码而言,无论是否实际出现错误,它都只会继续输出SUCCESS。
2 个解决方案
#1
3
You need to send an http status code other than 200:
您需要发送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"]));
}
Also, when sending json, set the content type accordingly, and never try and manually build a json string, use the built in json_encode
function instead, and its a good idea to use die()
or exit()
rather than echo
, to avoid any accidental additional output
另外,在发送json时,相应地设置内容类型,并且永远不要尝试手动构建json字符串,而是使用内置的json_encode函数,并且最好使用die()或exit()而不是echo,以避免任何意外的额外输出
That said, although sending appropriate status codes seems like a good idea, you may well find it a lot easier to always return 200 and parse the response, and keep the error handler for unexpected errors
也就是说,尽管发送适当的状态代码似乎是一个好主意,但您可能会发现总是返回200并解析响应更容易,并保留错误处理程序以应对意外错误
更多相关文章
- PHP强大包括处理错误?
- 您是否认为PHP中的错误形式是在类方法中访问超级全局变量?
- 解析错误:语法错误,第12行/home/public_html/gigs.html中的意外T_L
- eclipse 编写php错误
- php mail函数一段好的代码
- 我无法定义我的错误
- 用于上传多个文件的PHP代码
- php中的错误级别
- (phpQuery)对网站产品信息采集代码的优化