1 回答
TA贡献1847条经验 获得超7个赞
问题是,由于您是动态添加字段,因此 DOM 不知道它们存在。
您所要做的就是拨打电话,form.serialize()以便从表单字段中获取所有数据。
我创建了一个小型工作示例,以便您可以了解应该做什么:
$(document).ready(function() {
var form = $('form');
var fields = $('#fields');
var add_button = $('#add');
add_button.click(function(event) {
console.log('Add a new field');
// Notice I'm using backtick instead of quotes
// It's easier to read and add data dinamically
fields.append(`
<div>
<label for="field_${count}">Field #${count}</label><br />
<input type="text" name="field_${count}" id="field_${count}" />
</div>
`);
count++;
});
var count = 1;
var submit_button = $('#submit');
submit_button.click(function(event) {
event.preventDefault();
// Executes an AJAX's POST request
$.post(
// replace with the URL that will process the POST request
'https://jsonplaceholder.typicode.com/posts',
// here is where the magic happens
// form.serialize get data from all fields
// in your form object and submit them via AJAX
form.serialize(),
// Here you process the server's response
function(data) {
// do something with your data
console.log(data);
}
);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form" method="post">
<div>
<input type="button" id="add" value="Add" />
</div>
<div id="fields">
<div>
<label for="first_name">First Name</label><br />
<input type="text" name="first_name" id="first_name" />
</div>
<div>
<label for="first_name">Last Name</label><br />
<input type="text" name="last_name" id="last_name" />
</div>
</div>
<div>
<input type="submit" name="submit" id="submit" value="Submit" />
</div>
</form>
- 1 回答
- 0 关注
- 92 浏览
添加回答
举报