我有以下 HTML 和 jQuery Ajax 代码:
<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);
}
});
});
});
这是我的 PHP 代码:
<?php
$name = $_POST['name_field'];
?>
当我提交表单时,它显示以下错误:
Undefined index: name_field
但是,当我将 jQuery Ajax 更改为不等待 .error
类完成时,它不会显示任何错误并且工作得很好:
$(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);
}
});
});
为什么会出现这种情况以及如何修复它?
最佳答案
这是因为 this
引用用于序列化,在 hide
回调中它引用的是 error
元素而不是表单元素
$(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);
}
});
});
});
关于javascript - 让函数等待事件结束后出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21198533/