在 Symfony2 控制器中处理 Ajax 错误

2023-12-24

我正在尝试处理 Ajax 中的错误。为此,我只是想重现这个那么问题 https://stackoverflow.com/questions/407596/how-do-you-handle-errors-from-ajax-calls在交响乐中。

$.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 响应吗?

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

非常感谢


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

or

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;
}

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

public function ajaxAction()
{
    return new JsonResponse(array('message' => ''), 419);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Symfony2 控制器中处理 Ajax 错误 的相关文章

随机推荐