dongwen2896 2014-01-18 00:37
浏览 21
已采纳

使函数等待直到事件结束后出错

I have the following HTML and jQuery Ajax code:

<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);
            }
        });
    });
});

This is my PHP code:

<?php

    $name = $_POST['name_field'];

?>

When I submit the form, it shows the following error:

Undefined index: name_field

However, when I change my jQuery Ajax to not wait for the .error class to finish, it shows no error and works perfectly fine:

$(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);
        }
    });
});

Why does it do this and how can I fix it?

  • 写回答

1条回答 默认 最新

  • doula2426 2014-01-18 00:39
    关注

    It is because of the this reference used for serialization, inside the hide callback it refers to the error element not the form element

    $(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);
                }
            });
        });
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本