2016-11-10 146 views
2

我剛剛添加了x-editable到我目前的Laravel項目。它工作得非常好,但我有一個問題返回錯誤消息Laravel - 如何返回json錯誤消息?

當控制器能夠保存請求時,我得到'成功'! json消息。沒關係。但是當我有一個錯誤時,我不會得到'錯誤!'信息。正如你所看到的,當$ article-> save()沒有成功時,我激活了錯誤消息。

我在做什麼錯?

控制器:

$article->$input['name'] = $input['value']; 

if($article->save()){ 
    // this works 
    return response()->json(array('status'=>'success', 'msg'=>'Success!.'), 200); 
} 

else{ 
    // this does not work 
    return response()->json(array('status'=>'error', 'msg'=>'Error!'), 500); 
} 

的JavaScript在瀏覽:

$(".xeditable").editable({ 
    success: function(response) { 
     console.log(response.msg); 
    }, 
    error: function(response) { 
     // console says, that response.msg is undefinded 
     console.log(response.msg); 
    } 
}); 

親切的問候。

+0

你可以嘗試打印迴應嗎? – AShly

+2

您可以將此塊放在try catch上,並在catch上返回錯誤響應。 – Matheus

回答

0

我不熟悉x-editable但嘗試從500在錯誤的情況下改變響應代碼200,然後在你的JavaScript

$(".xeditable").editable({ 
    success: function(response) { 
     if (response.status == 'error') { 
      console.log('error: ' + response.msg); 
     } 
     else { 
      // do stuff for successful calls 
      console.log('success: ' + response.msg); 
     } 
    }, 
    error: function(xhr, status, error) { 
     console.log('server error: ' + status + ' ' + error); 
    } 
}); 
0

error回調,傳遞response參數是jqXHR(jQuery XMLHttpRequest )。爲了訪問JSON響應,您可以訪問responseJSON屬性,如下面的代碼。

$(".xeditable").editable({ 
    success: function(response) { 
    console.log(response.msg); 
    // Must return nothing. 
    }, 
    error: function(response) { 
    // The JSON object stored in responseJSON property. 
    console.log(response.responseJSON.msg); 

    // Must return a string, represent the error message. 
    return response.responseJSON.msg; 
    } 
}); 

正如指出的X-編輯文檔時,error回調必須返回一個代表錯誤信息的字符串。

希望得到這個幫助!