-->

手柄的Symfony2控制器内的Ajax错误(Handle errors in Ajax withi

2019-09-22 08:30发布

我想在Ajax来处理错误。 对于这一点,我只是想重现这一SO问题中的Symfony。

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

但我不能弄清楚在控制器中的代码将是什么样子在Symfony2中触发header('HTTP/1.0 419 Custom Error'); 。 是否有可能附上个人信息与这一点,例如You are not allowed to delete this post 。 我需要发送一个JSON响应吗?

如果任何人都熟悉这一点,我会很感激你的帮助。

非常感谢

Answer 1:

在你的行动,你可以返回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);
}

要么

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你可以返回的一个实例Symfony\Component\HttpFoundation\JsonResponse (感谢thecatontheflat的提示)。 使用这个类的优势在于它也会发出正确的Content-type头。 例如:

public function ajaxAction()
{
    return new JsonResponse(array('message' => ''), 419);
}


文章来源: Handle errors in Ajax within Symfony2 controller