定位多个表单以通过ajax发送(jquery)

vin*_*per 5 ajax jquery

我的页面上有多个表单.当我单击表单提交按钮时,我想通过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>
Run Code Online (Sandbox Code Playgroud)

Sia*_*agh 11

不要对多个元素使用相同的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>
Run Code Online (Sandbox Code Playgroud)