定位多个表单以通过ajax发送(jquery)
我的页面上有多个表单。 当我单击表单提交按钮时,我想通过ajax仅发送该表单的表单值。 这就是我所拥有的。 第一种forms作为其应有的,第二种forms实际上提交forms。 如何单独定位每个表单。 我觉得我应该在某个地方使用.find()。
// this is the id of the submit button $("#update_form").click(function() { $.ajax({ type: "POST", url: "approve_test.php", data: $(this.form).serialize(), // serializes the form's elements. success: function(data) { alert(data); // show response from the php script. } }); return false; // avoid to execute the actual submit of the form. });
不要对多个元素使用相同的id。 请改用类。
将您的代码更改为:
首先,在提交按钮中使用class。 请注意,ID是唯一的(根据w3c规范)
然后在你的onclick监听器中,使用最接近的forms获取表单(与父级相同但是以特定父级为目标;在这种情况下,它是表单元素)。 这是工作代码:
你在这里做什么有一些问题。
具有相同ID的多个元素:
从标记开始,可以看出form1
和form2
对于各自的提交按钮具有相同的id
。 这不是有效的标记。 你应该将它们设置为诸如form1-submit
和form2-submit
。
确定要提交的表单
在AJAX请求的data属性中,要标识要提交的表单,可以使用:
data: $(this).parent().serialize(),
现在,为了避免代码重复,通过为两个按钮中的每一个创建处理程序,将两个提交按钮都设置为相同的类,并将onclick
事件处理程序附加到该类,如下所示:
//Submit buttons //Event handler $('.submit-buttons').click(function(){ //Your code here });
请尝试以下方法:
var form = $('#form1', '#form2').serialize(); $.ajax({ type: "POST", url: "approve_test.php", data: form, success: function(data) { alert(data); // show response from the php script. } });