2012-05-27 45 views
0

我有文本框郵政數組到PHP使用jQuery

<input type="text" name="txt[]" id"txt[]" value="test 1" /> 
<input type="text" name="txt[]" id"txt[]" value="test 2" /> 
<input type="text" name="txt[]" id"txt[]" value="test 3" /> 

的陣列,並希望使用jquery發佈此數組PHP文件:

$('#submit').click(function() { 

     $.ajax({ 
      type : 'POST', 
      url : '<?php echo site_url('projects/create'); ?>', 
      data: { 
       txt: $('#txt').val() 
      }, 
      success:function (data) { 
       $("#log_msg").html(data); 
      }   
     }); 
    }); 

但它返回undefined

+0

您使用的是選擇#這是id。而一個文本框的id是「txt []」 –

回答

1

只要寫

<input type="text" name="pro_video[]" id="pro_video" /> 

$('#submit').click(function() { 

var videos = $('input[name^=pro_video]'); 
     var postData = { 
      vdo: [], // the videos is an array 
     }; 
     $.each(videos, function(index, el) { 
      // push the value in the vdo array 
      postData.vdo.push($(el).val()); 
     }); 

     $.ajax({ 
      type : 'POST', 
      url : '<?php echo site_url('projects/create'); ?>', 
      data: { 
       pro_video : postData 
      }, 
      success:function (data) { 
       $("#log_msg").html(data); 
      }   
     }); 
    }); 
0

你可以使用jQuery serialzie()從html表單中獲取表單值。

例如:

<form id="testForm" method="post"> 
    <input type="text" name="txt[]" id"txt[]" value="test 1" /> 
    <input type="text" name="txt[]" id"txt[]" value="test 2" /> 
    <input type="text" name="txt[]" id"txt[]" value="test 3" /> 
</form 

和抓取使用jQuery從表格的值。

$('#testForm').serialize(); 
0

jQuery $(form).serialize()函數將幫助你在這裏!

$('#submit').click(function() { 

     $.ajax({ 
      type : 'POST', 
      url : '<?php echo site_url('projects/create'); ?>', 
      data: $('#testForm').serialize(), 
      success:function (data) { 
       $("#log_msg").html(data); 
      }, 
      error: function(x,t,e){ 
       $("#log_msg").html('An error occured: '+e); 
      } 
     }); 
    }); 

你會得到一個$ _ POST非常乾淨的數組中的文件(無論SITE_URL(「項目/創建」)點)。警告,如果你添加一個輸入提交到那個表單,serialize()也會提交提交值,所以如果你打算直接在數據庫中插入數組,你必須從POST數組中刪除它。無論如何。 ;)

玩得開心! PS:id「txt []」對我來說似乎不是一個正確的標記......! ID = 「txt_1」。您的文檔中只能有一個參考ID,我認爲您不能在標記提示中使用括號。 (有人糾正我,如果我錯了......)

0

要將數組從JavaScript傳遞到PHP,您可以使用JQuery中的serialize function。您可以將其傳遞給整個表單或一些選定的表單元素。對於例如,你給它應該是這樣的:

的HTML:

<input type="text" name="txt[]" class="txt" value="test 1" /> 
<input type="text" name="txt[]" class="txt" value="test 2" /> 
<input type="text" name="txt[]" class="txt" value="test 3" /> 

和JavaScript:

$('#submit').click(function() { 

    $.ajax({ 
     type : 'POST', 
     url : '<?php echo site_url('projects/create'); ?>', 
     data: { 
      txt: $('.txt').serialize() 
     }, 
     success:function (data) { 
      $("#log_msg").html(data); 
     }   
    }); 
}); 

這會給你的PHP字符串「TXT%5B%5D = test + 1 & txt%5B%5D = test + 2 & txt%5B%5D = test + 3「,它可以解釋爲這些值的數組。

請注意,我使用類而不是id,因爲id應該是每個元素都是唯一的。