我有一个使用 PHP 动态创建的 Bootstrap 页面,该页面上有超过 25 个用于编辑记录的表单。
表单使用 jQuery Ajax 脚本提交到服务器,该脚本在第一个表单上按预期工作,但是当编辑并提交第二个表单时,它会提交表单 1 和 2,当我转到表单 3 时,它将提交表单 1 、2、3 这是 HTML:
<tr id="375987">
<td width="20%">audio controls to play wav file</td>
<td width="80%">
<div class="form-group">
<form id="375987">
<textarea class="form-control" id="rec_txt" name="rec_txt" rows="4">There is text from the Database</textarea>
<input type="text" id="event_num" name="event_num" value="" />
<button type="submit" id="correct_stt" class="btn btn-outline-success my-2 my-sm-0" OnClick="update_stt()">Edit</button>
<input type="hidden" id="rec_id" name="rec_id" value="375987" />
<input type="hidden" name="act" value="correct_stt" />
</form>
</div>
</td>
<td>
<a href="#" class="btn btn-primary a-btn-slide-text" onClick="hiderow('375987')">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
<span><strong>Hide</strong></span>
</a>
</td>
</tr>
<!-- 25+ forms ..... -->
这是 Java:
function update_stt() {
var url = "function_ajax.php"; // the script where you handle the form input.
$('form[id]').on('submit', function(e) {
$.ajax({
type: 'POST',
url: url,
data: $(this).serialize(),
success: function(data) {
console.log('Submission was successful.');
console.log(data);
$(e.target).closest('tr').children('td,th').css('background-color', '#000');
},
error: function(data) {
console.log('An error occurred.');
console.log(data);
},
});
e.preventDefault();
});
}
如何仅识别我要提交的表单的 ID,或仅提交该行上的表单?
最佳答案
您使用 submit
按钮将自动提交表单,但您还可以使用onclick
向其添加单击事件属性,因此它将执行关联的函数并提交表单。所有这些都不必要地复杂。
删除onclick
按钮上的属性:
<button type="submit" id="correct_stt" class="btn btn-outline-success my-2 my-sm-0">Edit</button>
并将您的代码更改为:
$('#375987').on('submit', function(e) {
var url = "function_ajax.php"; // the script where you handle the form input.
$.ajax({
type: 'POST',
url: url,
data: $(this).serialize(),
success: function(data) {
console.log('Submission was successful.');
console.log(data);
$(e.target).closest('tr').children('td,th').css('background-color', '#000');
},
error: function(data) {
console.log('An error occurred.');
console.log(data);
},
});
e.preventDefault();
});
如果您希望所有表单都使用相同的功能,则只需替换选择器 $('#375987')
与 $('form')
:
$('form').on('submit', function(e) { ... }
如果您只想选择某些表单,而不是全部,那么您可以给它们相同的类,然后按该类选择它们,例如 <form class="ajaxed">
:
$('form.ajaxed').on('submit', function(e) { ... }
关于javascript - 使用 jQuery 在页面上提交 1 个 Ajax 表单,其中包含多个独特的表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49431510/