【问题标题】:Handle errors in Ajax within Symfony2 controller在 Symfony2 控制器中处理 Ajax 中的错误
【发布时间】:2012-09-12 10:15:15
【问题描述】:

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

$.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 symfony-2.1


    【解决方案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);
    }
    

    【讨论】:

    • 在 Symfony 2.1 中的 AFAIK 你可以返回 JsonResponse()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    • 2016-11-06
    • 2020-04-09
    • 1970-01-01
    • 2016-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多