我有一个表单,带有文本输入和提交按钮。
提交时,我想首先访问服务器以查看输入是否有效,然后根据响应显示错误消息,或者如果有效,则继续表单提交。
这是我所拥有的:
$('#new_user').submit(function(e) {
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $('#new_user').serialize(),
success: function(data){
if (data.valid) {
return true
} else {
// Show error message
return false;
e.preventDefault();
}
}
});
});
问题是表单总是在提交,考虑到用例,正确的实现方法是什么?谢谢
最佳答案
尝试这样:
$('#new_user').submit(function(e) {
var $form = $(this);
// we send an AJAX request to verify something
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $form.serialize(),
success: function(data){
if (data.valid) {
// if the server said OK we trigger the form submission
// note that this will no longer call the .submit handler
// and cause infinite recursion
$form[0].submit();
} else {
// Show error message
alert('oops an error');
}
}
});
// we always cancel the submission of the form
return false;
});
关于javascript - 给定一个表单提交,如何仅在服务器首先使用有效标志响应时才提交?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9711802/