我想通过 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
不存在,所以没有什么可以绑定(bind)事件处理程序。
移动脚本使其出现在表单之后,或将其转换为函数并将其绑定(bind)为 ready
或 load
事件处理程序。
关于javascript - AJAX 表单脚本未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27346326/