2012-08-27 113 views
0

我在發送數據到Rails控制器的JavaScript中有一個ajax請求。如果控制器發現該數據與數據庫中已存在的信息重複,則返回「不可處理的實體」錯誤。如何在jQuery返回錯誤時重新發送ajax請求?

我想打開一個對話框,詢問用戶他是否確定要插入重複信息。如果用戶說是,我想添加另一個鍵到數據對象並重試請求。添加的密鑰將是一個忽略重複檢查並插入數據的標誌。

$.ajax({ 
     url: '/url', 
     type: 'post', 
     data: this.buildData(), 
     success: function() { 
     bootbox.alert('Information added', function() { 
      Backbone.history.loadUrl(); 
      }.bind(this) 
     ); 
     }.bind(this), 
     error: function(jqXHR, textStatus, errorThrown) { 
     if(errorThrown === 'Unprocessable Entity') { 
      bootbox.confirm('Do it anyway?', function(confirm) { 
       if(confirm) { 
       /*Here I want to add another key to the data object and resend the request*/ 
       } 
      }.bind(this) 
      ); 
     } 
     }.bind(this) 
    }); 

我怎麼會去這樣做,或者更好的是,有沒有做什麼,我試圖完成的更好的辦法?

+0

把ajax調用函數。 無論何時出現錯誤,請再次調用該函數。 – insomiac

回答

0

首先我肯定有一些插件。

但是,如果沒有插件是適合給我一些時間,以確保這個正常運行,充分代碼

另一種方式,你可能會感興趣使用你總是可以做這樣的事情

function dispatchAjax(options){ 

    options = $.extend({},options); 
    var data = $.extend({}, this.buildData(), options.data); 
    $.ajax({ ... , 
        error : function() { .... 
          if (typeof(options.retry) == "function"){ 
            var retryFunc = options.retry; 
            options.retry = null; 
            options.data = { "extraKey":"extraValue"}; 
            dispatchAjax(options); 
          } 
      }); 

} 

同步呼叫。 JQuery的ajax請求中的{"async":false}

我知道這可能似乎擊敗了目的,但是我發現它對於服務器端驗證非常有用 - 因此它可能適合您的需求,您將不必處理複雜的處理程序,如上所示,它將簡單是這樣的:

var result = dipatchRequest(options, /*async*/ false, /*ignore-duplicates*/ false); 
    if (result.error && confirm(..)){ 
     dispatchRequest(options, true, true); 
    }