jQuery 在使用 ajax 时抓取错误的形式

jQuery grabbing wrong form when using ajax

本文关键字:取错误 抓取 ajax jQuery      更新时间:2023-09-26

我有一个php函数,它循环通过数据库中的匹配项进行循环,在循环中,有一个表单返回到调用该函数的页面:

    while($row=mysql_fetch_array($get_unconfirmed))  
{ 
echo "<form name='confirm_appointment' method='post' class='confirm_appointment'>";
        echo "<input type='hidden' name='app_id' value='$appointment_id'>";
        echo "<input type='hidden' name='clinic_id' value='$clinic_id'>";
        echo "<td><input type='submit' class='update_appointment_button' value='$appointment_id'></td>";    
        echo "</form>"; 
}

然后我有jQuery提交表单:

$( document ).ready(function() {
    $(".update_appointment_button").click(function(){
        var url = "ajax/update_appointment_status.php";
        $.ajax({
               type: "POST",
               url: url,
               data: $(".confirm_appointment").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.
    });
});

但问题是,它的设置方式,无论我按"提交"哪一行 - 我总是从最后一行(表单)获取值。

所以我知道这个问题,我不是告诉jQuery通过按下按钮从表单中获取值。我需要以某种方式使用 .this,但似乎无法找出正确的语法。

任何帮助都将得到赞赏!

您可以像这样访问其父窗体

data: $(this).closest(".confirm_appointment").serialize(),

或类似的东西

data: $this.parent().parent().serialize(), 

另一种方法:将按钮click事件替换为表单submit事件。

$(document).ready(function () {
    $('.confirm_appointment').submit(function (e) {
        e.preventDefault();
        var url = "ajax/update_appointment_status.php";
        var serialized = $(this).serialize();
        $.ajax({
            type: "POST",
            url: url,
            data: serialized,
            success: function (data) {
                alert(data); // show response from the php script.
            }
        });
    });
});

JSFiddle 演示