我在控制器中有这部分代码,但是当我做这个动作和IF工作正常,错误消息出现在控制台日志中。抛出异常,但JSON响应获取状态SUCCESS
但它看起来像'成功'具有地位。而且它不应该
Try {
if ($last['date']) {
if ($last['date']->format('d-m-Y') == $par['date']) {
throw new \Exception('error', 500);
}
}
return new JsonResponse([
'success' => true,
'data' => $content,
'message' => 'success'
]);
} catch (\Exception $exception) {
return new JsonResponse([
'success' => false,
'code' => $exception->getCode(),
'message' => $exception->getMessage(),
]);
}
JQuery的
$.ajax({
type: "POST",
url: "/app/url",
data: TableData,
dataType: "json",
success: function(response){
console.log(response.message);
$('#message').html('<p class="alert alert-success">' + response.message + '</p>');
},
error: function (response) {
console.log(response.message);
$('#message').html('<p class="alert alert-danger">' + response.message + '</p>');
}
});
要报告错误,您必须返回400或500范围内的HTTP响应。在您当前的实施中,您提出了成功回复的请求。该响应包含一段Json,它正好具有属性“success”,其值为“false”,但您的Ajax调用并不知道这表明了错误。您可以通过解析响应来在JavaScript中实现,但更好,更纯粹的方法是让PHP返回适当的错误响应代码。请参阅[HTTP状态代码](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes) – GolezTrol
但是,当我抛出异常时不应该使用CATCH块吗? – Ferror
好吧,所以不要抛出异常,我应该重新成功回应:错误 – Ferror