我想在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响应吗?
如果任何人都熟悉这一点,我会很感激你的帮助。
非常感谢
在你的行动,你可以返回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);
}