簡體   English   中英

如何通過AJAX提交相同名稱的文本框值

[英]How do I submit the same name textbox value through AJAX

我有很多通過jQuery動態添加的文本框。 他們都有同樣的名字......

<input type="text" name="employer" id="employer" />
<input type="text" name="position" id="position" />
<input type="text" name="city" id="city" />

<input type="text" name="employer" id="employer" />
<input type="text" name="position" id="position" />
<input type="text" name="city" id="city" />

so many...

我通過AJAX傳遞所有文本框值,但它無法正常工作。 我的AJAX代碼在下面..

AJAX

$.ajax(
    {
      type: "POST",
      url: $("#cfgRoot").val()+'/accounts/educationInfoPost.php',
      data:
      {
        employer:$("#employer").val().trim(),
        position:$("#position").val().trim(),
        city:$("#city").val().trim()
      }
});

提前致謝

var empName = $("input[name=employer]").map(function(){
   return $(this).val();
}).get().join(",");

並將其傳遞給ajax數據。


var empName = $("input[name=employer]").map(function(){
   return $(this).val();
}).get().join(",");

var position = $("input[name=position]").map(function(){
   return $(this).val();
}).get().join(",");

var city = $("input[name=city]").map(function(){
   return $(this).val();
}).get().join(",");


$.ajax(
{
    type: "POST",
    url: $("#cfgRoot").val()+'/accounts/educationInfoPost.php',
    data:
    {
        employer:empName,
        position:position,
        city:city
    }
});

還有一件事是不要為DOM添加相同的ID。

ID必須是每個DOM的唯一

當您為2個輸入提供相同的名稱而且相同的ID時,您認為會發生什么?

如果您有多個輸入,您想要它們作為相同的名稱,您應該至少給它們相似的名稱。

就像是

<input type="text" name="employer1" class="employer" />
<input type="text" name="position1" class="position" />
<input type="text" name="city1" class="city" />

或者,您可以將它們提供給數組

<input type="text" name="employer[]" class="employer" />
<input type="text" name="position[]" class="position" />
<input type="text" name="city[]" class="city" />

至於通過AJAX發送這些數據,您可能只想序列化整個表單。 當然,這是基於您希望一次性發送所有表單數據的假設。

var serializedForm = $('form').serialize();
$.ajax(
{
    data: serializedForm,
    //rest of the code here
});

您的字段ID不是唯一的,請嘗試使您的ID唯一,並且它應該有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM