在Symfony2控制器中处理Ajax中的错误

Mic*_*ick 9 symfony symfony-2.1

我正在尝试处理Ajax中的错误.为此,我只是想在Symfony中重现这个SO问题.

$.ajaxSetup({
    error: function(xhr){
        alert('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText);
    }
});
Run Code Online (Sandbox Code Playgroud)

但是我无法弄清楚控制器中的代码在Symfony2中会是什么样子来触发header('HTTP/1.0 419 Custom Error');.例如,是否可以附加个人信息You are not allowed to delete this post.我是否也需要发送JSON响应?

如果有人熟悉这一点,我将非常感谢你的帮助.

非常感谢

Flo*_*fer 14

在您的操作中,您可以返回一个Symfony\Component\HttpFoundation\Response对象,您可以使用该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);
}
Run Code Online (Sandbox Code Playgroud)

要么

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;
}
Run Code Online (Sandbox Code Playgroud)

更新:如果您使用的是Symfony 2.1,则可以返回一个实例Symfony\Component\HttpFoundation\JsonResponse(感谢thecatontheflat提示).使用此类的优点是它还将发送正确的Content-type标头.例如:

public function ajaxAction()
{
    return new JsonResponse(array('message' => ''), 419);
}
Run Code Online (Sandbox Code Playgroud)

  • 在Symfony 2.1中的AFAIK你可以返回`JsonResponse()` (3认同)