[英]Use jQuery to submit 1 Ajax form on page with several unique forms
我有一個使用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
屬性向其添加了一個click事件,因此它將執行關聯的功能並提交表單。 所有這些都是不必要的復雜。
刪除按鈕上的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) { ... }
您可以為表單提供ID並使用
$('#formid').submit();
在你的情況下
$('#375987').submit();
但是您的tr div也使用了該ID。 您應該考慮僅將id用於表單
這是因為每次單擊按鈕並調用update_stt()
您都將再次附加.on()
偵聽器。
這就是為什么您最終收到越來越多的提交請求的原因。
$('form[id]').on('submit', function (e) {
此代碼行僅應在每次單擊時調用一次。
還:您說您在后端構建這些,以便可以將ID直接傳遞給函數:
update_stt(375987)
然后,您可以使用以下代碼:
function update_stt(passedNumber) { ...
然后您可以在通話中使用ID號
在這里大量使用jQuery和Vanilla JS混合,嘗試更大的重構可能是有意義的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.