我的页面上有多种形式。当我单击表单提交按钮时,我想通过ajax仅发送该表单的表单值。这就是我所拥有的。第一种形式按预期工作,第二种形式实际提交表单。如何分别定位每个表单。我觉得我应该在某个地方使用.find()。
<form id="form1" method="post"> <input type="text" id="name1" name="value" value=""> <input type="submit" id="update_form" value="Save Changes"> </form> <form id="form2" method="post"> <input type="text" id="name2" name="value" value=""> <input type="submit" id="update_form" value="Save Changes"> </form> <script> // 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. }); </script>
请勿对多个元素使用相同的ID。使用类代替。 将代码更改为此:
<form id="form1" method="post"> <input type="text" id="name1" name="value" value=""> <input type="submit" class="update_form" value="Save Changes"> <!-- changed --> </form> <form id="form2" method="post"> <input type="text" id="name2" name="value" value=""> <input type="submit" class="update_form" value="Save Changes"> <!-- changed --> </form> <script> // this is the class of the submit button $(".update_form").click(function() { // changed $.ajax({ type: "POST", url: "approve_test.php", data: $(this).parent().serialize(), // changed success: function(data) { alert(data); // show response from the php script. } }); return false; // avoid to execute the actual form submission. }); </script>