Handle errors in Ajax within Symfony2 controller

两盒软妹~` 提交于 2019-12-08 16:23:20

问题


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

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.

Many thanks


回答1:


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

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


来源:https://stackoverflow.com/questions/12385923/handle-errors-in-ajax-within-symfony2-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!