在 Symfony2 控制器中处理 Ajax 中的错误 [英] Handle errors in Ajax within Symfony2 controller

查看:21
本文介绍了在 Symfony2 控制器中处理 Ajax 中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to handle errors in Ajax. For this, I am simply trying to reproduce this SO question in Symfony.

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

但我无法弄清楚控制器中的代码在 Symfony2 中会是什么样子来触发 header('HTTP/1.0 419 Custom Error');.是否可以附上个人信息,例如不允许删除此帖子.我也需要发送 JSON 响应吗?

but I can't figure out what the code in the controller would look like in Symfony2 to trigger header('HTTP/1.0 419 Custom Error');. Is it possible to attach a personal message with this, for example You are not allowed to delete this post. Do I need to send a JSON response too?

如果有人对此熟悉,我将非常感谢您的帮助.

If anyone is familiar with this, I would really appreciate your help.

非常感谢

推荐答案

在你的动作中你可以返回一个 Symfony\Component\HttpFoundation\Response 对象,你可以使用 setStatusCode 方法或第二个构造函数参数来设置 HTTP 状态代码.当然,如果您愿意,也可以将响应的内容作为 JSON(或 XML)返回:

In your action you can return a Symfony\Component\HttpFoundation\Response object and you can either use the setStatusCode method or the second constructor argument to set the HTTP status code. Of course if is also possible to return the content of the response as JSON (or XML) if you want to:

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 标头.例如:

Update: If you are using Symfony 2.1 you can return an instance of Symfony\Component\HttpFoundation\JsonResponse (Thanks to thecatontheflat for the hint). Using this class has the advantage that it will also send the correct Content-type header. For example:

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

这篇关于在 Symfony2 控制器中处理 Ajax 中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆