我正在关注这个 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/