2017-09-22 27 views
1

我是jQuery的新手。基本上我有一張桌子,我可以排列行。我想將新訂單保存在後臺,我可以做到這一點。但是,我注意到我發送多個Ajax調用取決於我排序表的次數。訂單在後端沒有正確保存。這是我的代碼。變量順序是新ID存儲的位置。我通過「/ updateorder」路線/發送它在我的Django在jQuery上避免多個AJAX調用sortable()

<script type="text/javascript"> 
    $(document).ready(function(){ 
    $("#sortable").sortable({ 
     update: function (event, ui) { 
     var order = $(this).sortable('toArray'); 
     console.log(order); 

     $(document).on("click", "button", function() { 
      $.ajax({ 
      data: {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value, 'order[]': order}, 
      type: 'POST', 
      url: '/updateorder' 
      }) 
     }); 
     } 
    }).disableSelection(); 
     $('button').on('click', function() { 
     var r = $("#sortable").sortable("toArray"); 
     var a = $("#sortable").sortable("serialize", { 
      attribute: "id" 
     ); 
     console.log(r); 
     }); 
    }); 
</script> 

我怎樣才能避免發送當我按一下按鈕多個Ajax調用?另外,在邏輯執行後重定向到不同頁面的正確方法是什麼?謝謝閱讀!

PS:我使用Python/Django的在後端

+0

你需要取消先前的請求,如果有另一個,試着看看這裏https://stackoverflow.com/questions/19244341/abort-previous-ajax-request-on-new-request – lub0v

+0

你好,我試過了代碼每你的鏈接,我做了一些修改,我仍然發送多個阿賈克斯電話:( – Marvin

回答

3

答案就在你的代碼。每次移動物品時都附加事件處理程序。所以當你排序5個項目時,你將5個事件處理程序附加到你的提交按鈕。然後當你點擊按鈕時,所有5個事件處理程序立即啓動ajax調用。您應該在外部移動onclick事件處理函數,並通過函數參數或公共變量傳遞變量。

+0

OMG!非常感謝! – Marvin