2016-10-05 103 views
1

我想通過一系列輸入從表單迭代。 foreach輸入我想要發出一個ajax調用,只有在前一個調用完成後纔會觸發。我在這裏閱讀Stack answerajax調用迭代通過JavaScript數組

$(function(){ 

var data = []; 

    $('input[type=text]').each(function(e,i){ 
      var val = $(this).val(); 
      data.push(val); 
    }); 

    current = 0; 
    function do_ajax() { 
      if (current < data.length) { 
        $.ajax({ 
          type:"POST", 
          data:"id="+data[current].value, 
          url:"tester.php", 
          success:function(result){ 
            $('#div').append(result); 
            current++; 
            do_ajax(); 
          } 
        }); 
      }; 
    } 
    do_ajax(); 
}); 

HTML

<input type='text' id='users[][name]' value='Bob'> 
    <input type='text' id='users[][name]' value='Frank'> 
    <input type='text' id='users[][name]' value='Tom'> 
    <input type='text' id='users[][name]' value='Joe'> 
    <input type='text' id='users[][name]' value='Bill'> 
    <input type='text' id='users[][name]' value='Gary'> 

<div id='done'></div> 
<div id='div'>DIV</div> 

tester.php測試很簡單:

echo $_POST['id']; 

我不能得到從tester.php返回任何東西,除了:

undefined 

做什麼我需要在數據中添加id ajax調用?

我曾嘗試:

data[current].value; 

data[current].val; 

data[current].val(); 

編輯::::::

使用接受的解決方案我也不得不改變:

$('#div').append(result); 

到:

$('#div').append(result.responseText); 
+0

爲什麼不乾脆把所有的數據一次 – adeneo

+0

這是我試圖做的一個精簡版本。我只發佈了足以讓我的問題。每個ajax調用都會構建前一個的結果。 – bart2puck

+0

好吧 - > https://jsfiddle.net/89ggmrgn/2/ – adeneo

回答

2

沒有value財產,改變這種:

data:"id="+data[current].value 

這樣:

data:"id="+data[current] 

,還可以使用complete代替success回調,因爲complete執行successerror回調

+0

數組是否構建「正確」(是不是索引不好的代碼)?我應該用index:value來創建它嗎?我應該使用一個對象嗎? – bart2puck

+0

實際上不得不撤回我的接受。 echo $ _POST ['id']的結果是0,1,2,3,4,5 – bart2puck

+0

您可以在網絡選項卡的開發人員工具中看到要提交的表單數據。 – vher2