javascript - 让函数等待事件结束后出错

标签 javascript php ajax jquery

我有以下 HTML 和 jQuery Ajax 代码:

<form>
    <input name="name_field" type="text">
    <button type="submit">Save</button>
</form>

$(document).on("submit", "form", function(event) {
    event.preventDefault();
    $(".error").hide("blind", function() {
        $.ajax({
            url: 'php/script.php',
            type: 'POST',
            dataType: 'json',
            data: $(this).serialize(),
            success: function(data) {
                console.log(data);
            }
        });
    });
});

这是我的 PHP 代码:

<?php

    $name = $_POST['name_field'];

?>

当我提交表单时,它显示以下错误:

Undefined index: name_field

但是,当我将 jQuery Ajax 更改为不等待 .error 类完成时,它不会显示任何错误并且工作得很好:

$(document).on("submit", "form", function(event) {
    event.preventDefault();
    $(".error").hide("blind"); // remove function() here
    $.ajax({
        url: 'php/script.php',
        type: 'POST',
        dataType: 'json',
        data: $(this).serialize(),
        success: function(data) {
            console.log(data);
        }
    });
});

为什么会出现这种情况以及如何修复它?

最佳答案

这是因为 this 引用用于序列化,在 hide 回调中它引用的是 error 元素而不是表单元素

$(document).on("submit", "form", function (event) {
    event.preventDefault();
    var $form = $(this);
    $(".error").hide("blind", function () {
        $.ajax({
            url: 'php/script.php',
            type: 'POST',
            dataType: 'json',
            //this here is not the form element it is the error element
            data: $form.serialize(),
            success: function (data) {
                console.log(data);
            }
        });
    });
});

关于javascript - 让函数等待事件结束后出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21198533/

相关文章:

javascript - 如何查看 iframe 的 410 状态?

ajax - aria-controls 究竟为用户做什么?它如何受 AJAX 使用的影响?

javascript - FullCalendar PHP 和 MySQL 集成,事件不更新

javascript - 在特定 View 的情况下隐藏部分按钮

javascript - 如果数组中存在重复值,则提醒用户

javascript - 从复选框中选择选中的值

php - 轮类日历 - 根据给定模式确定轮类

php - 如何使用多个where Codeigniter搜索数据

javascript - 使用 React 绘制 d3 轴,无需直接操作 D3 DOM

php - 使用流包装器迭代 S3 存储桶