2012-09-12 29 views
7

我正試圖處理Ajax中的錯誤。爲此,我只是想在Symfony中重現這個SO question在Symfony2控制器內處理Ajax中的錯誤

$.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響應?

如果有人熟悉這一點,我會非常感謝您的幫助。

非常感謝

回答

12

在你的行動,你可以返回一個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的實例(感謝提示的平臺)。使用這個類的優點是它也會發送正確的Content-type標題。例如:

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

AFAIK在Symfony 2.1中可以返回'JsonResponse()' –

+0

感謝您的提示。我更新了我的答案。 –