使用JQuery Ajax提交特定表单

我在页面上有很多具有相同ID的表单。 当我按下任何表格的提交按钮时,首先提交第一个,然后在第二个点击第二个…之后。 但我希望当我按下提交按钮时,表单将提交按钮所属的位置。 我怎样才能做到这一点。

这是我的JS代码:

$(document).on('submit','#ajax_form',function(e) { var form = $('#ajax_form'); var data = form.serialize(); $.post('game/write.php', data, function(response) { console.log(response); $('#power').replaceWith(response); }); return false; }); 

这里的HTMl代码:

 

这是您的问题开始的地方:

 var form = $('#ajax_form'); 

它选择第一个表单,而不是提交的表单。 只需将其替换为

 var form = $(this); 

会解决你的问题,但我仍然建议不要使用重复的ID。

如果你不知道提交哪个表单并且只想用一段代码处理所有表单的提交,那么这样就可以了…

 $(document).on('submit','form',function(e) { var form = $(this); var data = form.serialize(); $.post('game/write.php', data, function(response) { console.log(response); $('#power').replaceWith(response); }); return false; }); 

正如大家之前提到的,您不能将ID用于多个元素。 上面的代码将submit事件处理程序分配给所有表单,并使用$(this)来引用已提交的表单。 它应该做的伎俩:)

试试这个:

 $(document).on('click','button.btn',function(e) { //you will trigger this function when you click a button //this will select the parent, ie, the form var form = $(this).parent(); var data = form.serialize(); $.post('game/write.php', data, function(response) { console.log(response); $('#power').replaceWith(response); }); return false; }); 

ID必须在整个DOM中是唯一的。

只有一个元素可以具有相同的ID。 将您的函数设置为传递要提交的正确表单的ID。

最好使用class="ajax_form"而不是ID,然后应用$(this)

 $(document).on('submit','.ajax_form',function(e) { var form = $(this); var data = form.serialize(); // other code return false; });