我正在尝试处理Ajax中的错误。为此,我只是想在Symfony中重现这个SO问题。
$.ajaxSetup({
error: function(xhr){
alert('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText);
}
});
但我不知道控制器中的代码在Symfony2中会是什么样子来触发CCD_ 1。是否可以附加一条个人信息,例如You are not allowed to delete this post
。我是否也需要发送JSON响应?
如果有人对此很熟悉,我将非常感谢你的帮助。
非常感谢
在操作中,您可以返回SymfonyComponentHttpFoundationResponse
对象,也可以使用setStatusCode
方法或第二个构造函数参数来设置HTTP状态代码。当然,如果您想的话,也可以将响应的内容返回为JSON(或XML):
public function ajaxAction()
{
$content = json_encode(array('message' => 'You are not allowed to delete this post'));
return new Response($content, 419);
}
或
public function ajaxAction()
{
$response = new Response();
$response->setContent(json_encode(array('message' => 'You are not allowed to delete this post'));
$response->setStatusCode(419);
return $response;
}
更新:如果您使用Symfony 2.1,您可以返回SymfonyComponentHttpFoundationJsonResponse
的实例(感谢tontheflat提供的提示)。使用这个类的优点是它还将发送正确的Content-type
报头。例如:
public function ajaxAction()
{
return new JsonResponse(array('message' => ''), 419);
}