繁体   English   中英

AJAX表单脚本未执行

[英]AJAX form script isn't executed

我想通过AJAX使用表单,所以我从stackoverflow上的另一篇文章中获取了这个代码片段。 它没有用,所以我添加了一个警报来检查,如果脚本是执行的话。 情况似乎并非如此,我想知道为什么。

<head>
    <script src='jquery.js'></script>
    <script>
    var request;

    $("#foo").submit(function(event){

        alert("Hallu");

        if (request) {
            request.abort();
        }

        var $form = $(this);

        var $inputs = $form.find("input, textarea");

        var serializedData = $form.serialize();

        $inputs.prop("disabled", true);

        request = $.ajax({
            url: "/action.php",
            type: "post",
            data: serializedData
        });

        request.done(function (response, textStatus, jqXHR){
            // Log a message to the console
            console.log("Hooray, it worked!");
        });

        request.fail(function (jqXHR, textStatus, errorThrown){
            // Log the error to the console
            console.error(
                "The following error occurred: "+
                textStatus, errorThrown
            );
        });

        request.always(function () {
            // Reenable the inputs
            $inputs.prop("disabled", false);
        });

        event.preventDefault();
    });


   </script>
</head>
<body>
    <form id="foo">
        <input type="text" id="name" name="name" />
        <textarea id="msg" name="msg"></textarea>
        <input type="submit" value="Senden" />
    </form>
</body>

当脚本运行时, #foo不存在,因此没有任何东西可以绑定事件处理程序。

移动脚本使其显示在窗体之后,或将其转换为函数并将其绑定为readyload事件处理程序。

原因很简单。 你在加载之前对$('#foo')做了些什么。 此时JS对id =“foo”的对象一无所知,因为它尚未加载。

将整个代码包装在$(document).ready(function() { ... });

这应该是这样的:

var request;

$(document).ready(function() {

    $("#foo").submit(function(event){

        alert("Hallu");

        if (request) {
            request.abort();
        }

        var $form = $(this);

        var $inputs = $form.find("input, textarea");

        var serializedData = $form.serialize();

        $inputs.prop("disabled", true);

        request = $.ajax({
            url: "/action.php",
            type: "post",
            data: serializedData
        });

        request.done(function (response, textStatus, jqXHR){
            // Log a message to the console
            console.log("Hooray, it worked!");
        });

        request.fail(function (jqXHR, textStatus, errorThrown){
            // Log the error to the console
            console.error(
                "The following error occurred: "+
                textStatus, errorThrown
            );
        });

        request.always(function () {
            // Reenable the inputs
            $inputs.prop("disabled", false);
        });

        event.preventDefault();
    });
});

请考虑使用一个好的IDE,如NetBeans或Eclipse。 它可以帮助您检测未关闭的括号和其他内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM