javascript - 尝试在不离开页面的情况下使用 jquery ajax 发布

标签 javascript php jquery html ajax

我正在关注这个 question试图发布到 php 页面并让它对数据执行操作问题是它似乎只是刷新页面但不确定它在做什么。在元素检查器的网络选项卡中,我的 php 页面从未出现。 这是我的代码:

js:

<script>

$(函数(){ $("#foo").submit(函数(事件){ //保存请求的变量 变量请求; //绑定(bind)到我们表单的提交事件

// abort any pending request
if (request) {
    request.abort();
}
// setup some local variables
var $form = $(this);
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $form.serialize();

// let's disable the inputs for the duration of the ajax request
$inputs.prop("disabled", true);

// fire off the request to /form.php
request = $.ajax({
    url: "/DormDumpster/session/login-exec.php",
    type: "post",
    data: json
});

// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
    // log a message to the console
    console.log("Hooray, it worked!");
    alert("hello");
});

// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
    // log the error to the console
    console.error(
        "The following error occured: "+
        textStatus, errorThrown
    );
            alert("bye");

});

// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
    // reenable the inputs
    $inputs.prop("disabled", false);
});

// prevent default posting of form
event.preventDefault();

}); });

html:

        <form id = "foo" method="post" >
            <fieldset id="inputs">
                <input id="email" type="email" name="login" placeholder="Your email address" required>   <br>
                <input id="password" type="password" name="password" placeholder="Password" required>
            </fieldset>
            <fieldset id="actions"">
                <input type="submit" id="submit" name "Submit" value="Log in"">
                <label><input type="checkbox" checked="checked"> Keep me signed in</label>
            </fieldset>
        </form>

PHP

    $email = clean($_POST['login']);
    $password = clean($_POST['password']);

关于我做错了什么或如何弄清楚我做错了什么的任何想法。

最佳答案

您可能试图在表单在 DOM 中可用之前附加事件监听器 - 因此您的表单将找不到,也不会附加任何事件监听器。尝试将您的代码包装在 DOM 就绪回调中,以确保您的表单在尝试选择它之前位于 DOM 中。

$(function () {
    $("#foo").submit(function(event){
         // All your code...
    });
});

更多关于为什么何时使用 DOM 就绪回调的信息 here .

关于javascript - 尝试在不离开页面的情况下使用 jquery ajax 发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18909756/

相关文章:

javascript - 为 Shopify 开发设置 webpack/HMR

javascript - 当鼠标悬停在文本上时,jquery 工具提示不出现

循环内的javascript函数不起作用

java - 我能不能把 'bounce'一个文件上传到一台服务器直接发到另一台服务器?

javascript - 如何自动调整/调整 html5 textarea 元素的大小以适合初始内容?

jquery 添加类

javascript - 为什么我不能将参数传递给 addEventListener 中的匿名函数,如何解决?

javascript - 用于聊天应用程序或私有(private)应用程序的 Firebase 数据结构

php - 浮点后最多显示 2 位数字...仅当它是超过 2 个 float 字的 float 时

jquery表单验证不允许用户名字段有空格?