【发布时间】:2019-06-23 22:50:46
【问题描述】:
我遇到了关于使用 ajax 提交附加字段的障碍。
这是我的问题的描述。
我的 HTML 表单是
<div id="append-fields">
<input name="firstName[]" id="firstName" value="john"></input>
<input name="lastName[]" id="lastName" value="Doe"></input>
</div>
<button onclick="appendFunction()" type="button">Add a new row</button>
点击按钮add a new row 后,我得到更多这样的两个字段
<div id="append-fields">
<input name="firstName[]" id="firstName" value="anna"></input>
<input name="lastName[]" id="lastName" value="Kondo"></input>
</div>
现在我需要用ajax提交以下数据
firstName = 'john',lastName = 'Doe'
firstName = 'anna',lastName = 'kondo'
但我只得到一组这样的数据
firstName = 'john',lastName = 'Doe'
这是我的脚本
<script>
insert = [];
insert[0] = $("#firstName").val();
insert[1] = $("#lastName").val();
$.ajax({
url: 'myUrl',
method: 'POST',
data: {take:insert},
error: function () {
},
success: function (response) {
$('#overlay').addClass("hidden");
jQuery('#body').html(response);
}
});
</script>
这是我的 PHP
function myUrl(){
$data = $_POST["take"];
}
错在哪里?
【问题讨论】:
-
你不能(如果你想让事情正确)有 2 个
id属性,就像id="firstName"一样,每个添加的 html 块都有一次。 -
如果您使这些
id独一无二,您可以在 ajax 调用中将它们添加到您的数据结构中 -
或者在类名上使用
each.,并在 ajax 调用中将数据添加到您的数据结构中
标签: javascript php jquery ajax append