2015-12-07 92 views
0

我試圖從一個頁面中的許多列表向服務器發送數據,每個數據都會觸發ajax數據以供PHP進一步處理。我的代碼使用(class = dd)選擇每個列表並逐個發送ajax數據。當我在ajax成功後使用警報(響應)時,這非常有效,刪除此警報消息僅向服務器發送較少數量的列表(僅發送4個列表中的2個列表)。有什麼想法嗎?處理多個Ajax請求只有在提醒時纔有效

$('#submit_sorting').on('click', function() { 
     var testEmail = /^[A-Z0-9._%+-][email protected]([A-Z0-9-]+\.)+[A-Z]{2,4}$/i; 
     if (testEmail.test($('#user_email').val()) || $('#user_email').val()==""){ 
      $('[class=dd]').each(function(){ 
        var data = $(this).nestable('serialize'); 
        var dataJson = JSON.stringify(data); 
        console.log('sent '+JSON.stringify(data)); 
        var response = ajaxx(data); 
        alert(response); 
       }); 
     } 
     else 
     { 
      alert('enter valid email address'); 
     } 

    }); 

這裏是Ajax代碼

function ajaxx(data){ 
      return $.ajax({ 
      type: "POST", 
      url: 'cardsorting/update', 
      data: { 
       'new_order': data, 
       'user_comments':$('#user_comments').val(), 
       'user_email':$('#user_email').val(), 
       '_token':$('meta[name="_token"]').attr('content') 
      }, 
      success: function(data){ 
       if(data=='dataissaved'){ 
        console.log('came here '+$(location).attr('href')); 
       } 
      else 
      { 
        console.log('received '+JSON.stringify(data)); 

       } 

     }, 
      error: function (data) { 
       alert('Could not connect to controller'); 
      } 
     }); 
    } 
+0

試試這個$阿賈克斯({ ... 異步:假 }); – WisdmLabs

+0

$ .ajax是異步的...學習如何編碼異步代碼,其中說'async:false'將始終工作,它已被棄用firefox和鉻現在幾個月 –

+0

爲什麼你不發送所有的數據在數組並在「cardsorting/update」處理程序中處理? –

回答

0

這到底是如何工作的,而不是發送多個Ajax請求的每一個選擇,我收集他們在一個數組,然後將其AJAX來了後端php。

$('#submit_sorting').on('click', function() { 
    var sorting_array = new Array(); 
    var testEmail = /^[A-Z0-9._%+-][email protected]([A-Z0-9-]+\.)+[A-Z]{2,4}$/i; 
    var flag = false; 
    if (testEmail.test($('#user_email').val()) || $('#user_email').val()==""){ 
      $('[class=dd]').each(function(){ 
       var data = $(this).nestable('serialize'); 
       sorting_array.push(data); 
       console.log('sent '+JSON.stringify(data));    
      }); 
      flag = true; 
     } 
    else 
    { 
     alert('enter valid email address'); 
    } 
    if(flag){ 
     ajaxx(sorting_array); 
     console.log(JSON.stringify(sorting_array)); 
    } 

});