2017-02-22 35 views
3

我正在做一些Ajax第一次...代碼:即使在捕獲失敗時仍存在控制檯錯誤?

jQuery的

form_ajax_promise = $.ajax({ 
    type : "POST", 
    url : '/orders/create_or_update', 
    dataType: 'json', 
    contentType: 'application/json', 
    data : JSON.stringify(params) 
}) 
form_ajax_promise.then(
    function(response) { 
    formSuccess(response) 
    }, 
    function(response) { 
    formFailure(response) 
    } 
) 

控制器

def create_or_update 
    if @object.save 
    # corresponds with formSuccess 
    render json: {"id" => @order.id}, status: 200 
    else 
    # corresponds with formFailure 
    render json: {"errors"=> @order.errors.full_messages}, status: 400 
    end 
end 

success路徑效果很好。在測試failure路線,假設formFailure只是一個簡單的功能...

function formFailure(response){ 
    console.log("successfully inside of formFailure") 
} 

什麼我注意到正在發生的事情是,console顯示相應的日誌消息上面,同時也說明我的錯誤:

Failed to load resource: the server responded with a status of 400 (Bad Request) 

這個錯誤是否應該發生?我覺得自從我在$.then中提供了足夠的fail它不應該?

編輯

道歉的混亂,這不是多的情況下渲染/重定向,我只是懶惰和切割出的其他代碼,因爲我只是想描述失敗的行爲。我的錯。代碼在上面編輯。

+0

你正在做一個'status:400'的渲染,所以這是正確的行爲。 – Sajan

+0

兩個問題(1)哪個版本的jQuery? (2)'form_ajax_promise'是否進一步處理? –

+0

1)jQuery 2.2.4,2)它不被進一步處理 – james

回答

1

也許這樣的事情會做。這將返回success@order成功保存和error@order無效

def create_or_update 
    # Your code here to create or update @order 
    if @order.save 
    # corresponds with formSuccess 
    render json: {"id" => @order.id}, status: 200 
    else 
    # corresponds with formFailure 
    render json: {"errors"=> @order.errors.full_messages}, status: 400 
    end 
end 
+0

對不起,我只是縮寫代碼和懶惰,這是怎麼回事 – james

0

通常,這種類型的多渲染或重定向錯誤代碼的結果。如果不使用條件/分支語句(如if或return語句),則不要在同一個函數中使用多個呈現或重定向。

在你的情況,

render json: {"errors"=> @order.errors.full_messages}, status: 400

是被渲染,其引導的錯誤代碼400接收到瀏覽器(這是錯誤的請求),所以你看到在控制檯此錯誤。 更好地使用@Deepak Mahakale在上面分享的代碼。

希望這可以幫助

+0

對不起,看評論/編輯 – james

相關問題