php jQuery preventDefault() 在 AJAX 调用中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22763746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery preventDefault() not working inside AJAX call
提问by C. Ovidiu
So, I am doing a check when a user inputs an email to see if the email exists or not.
因此,当用户输入电子邮件以查看电子邮件是否存在时,我会进行检查。
$('form.recover-form#check-form').on('submit', function(e){
var form = $(this),
input = $('.check-recover-email'),
span = $('.recover-error'),
email = input.val();
span.text('');
e.preventDefault();
$.ajax({
url: 'ajax/check-email',
async: 'false',
cache: 'false',
type: 'POST',
data: {email: email},
success: function(response) {
if ( response == 'no' ) {
span.text('email does not exist');
} else if ( response == 'ok' ) {
form.submit();
}
}
});
});
The php code
php代码
if ( Input::isPost('email') ) {
$email = Input::post('email');
$check = $dbh->prepare(" SELECT * FROM users WHERE email = :email ");
$check->execute(array( 'email' => $email ));
echo ( $check->rowCount() == 1 ) ? 'ok' : 'no' ;
}
This way as soon as I submit the form it submits and the e.PreventDefault()
inside the AJAX call is not working. If I put e.PreventDefault()
before the AJAX call however, the form does not submit and the error appears if the email does not exists ( this is what I want to achieve ).
这样,只要我提交它提交的表单,并且e.PreventDefault()
AJAX 调用内部就不起作用。e.PreventDefault()
但是,如果我在 AJAX 调用之前放置,则表单不会提交,并且如果电子邮件不存在则会出现错误(这是我想要实现的)。
I can't understand where the problem is, hope you can help.
我不明白问题出在哪里,希望你能帮忙。
Thank you.
谢谢你。
EIDT: This is the updated code
EIDT:这是更新的代码
回答by T.J. Crowder
The problem is that you don't call preventDefault
during the handling of the event. Instead, during the handling of the event, you startan ajax call (which is asynchronous), and then let the event continue. The ajax call completes later, which is too late to prevent the event's default — it's already happened.
问题是您preventDefault
在处理事件期间没有调用。相反,在处理事件期间,您启动一个 ajax 调用(这是异步的),然后让事件继续。ajax 调用稍后完成,这已经太晚了,无法阻止事件的默认设置——它已经发生了。
Move the e.preventDefault()
directly into the event handler, outside the ajax success
handler.
将e.preventDefault()
直接移动到 ajaxsuccess
处理程序之外的事件处理程序中。
$('.recover-form').on('submit', function(e){
var form = $(this),
input = $('.check-recover-email'),
span = $('.recover-error'),
email = input.val();
span.text('');
e.preventDefault(); // <=================== Here
$.ajax({
url: 'ajax/check-email',
async: 'false',
cache: 'false',
type: 'POST',
data: form.serialize(),
success: function(response){
if ( response == 0 ) {
// ============================ Not here, this would be too late
span.text('email does not exist');
}
}
});
});
In a comment, you've said:
在评论中,您曾说过:
Yes, it works for the validation, but I want to submit the form if ajax returns a positive response. I only do a check with AJAX, if it fails stop the submit, if it succeed continue the submit.
是的,它适用于验证,但如果 ajax 返回肯定响应,我想提交表单。我只用 AJAX 做一个检查,如果它失败停止提交,如果它成功继续提交。
You can't hold up the original form submission waiting for the result of an asynchronous ajax call. What you do instead is cancel the original form submission, do the ajax, and then if the result is okay, re-submit the form using the submit
method on the raw DOM form
element. That method doesn't re-trigger submit
event handlers.
你无法阻止原始表单提交等待异步ajax调用的结果。相反,您要做的是取消原始表单提交,执行ajax,然后如果结果正常,则使用submit
原始DOMform
元素上的方法重新提交表单。该方法不会重新触发submit
事件处理程序。
Example: Live copy
示例:实时复制
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset=utf-8 />
<title>Delaying form submit during ajax</title>
</head>
<body>
<form action="http://www.google.com/search" method="GET">
<input type="text" name="q" value="kittens">
<input type="submit" value="Submit">
</form>
<script>
(function() {
$("form").submit(function(e) {
var rawFormElement = this; // Remember the DOM element for the form
// Stop form submission
display("Got form submit event, simulating ajax");
e.preventDefault();
// Simulate ajax check of data
setTimeout(function() {
// (This is the 'success' callback for the ajax)
display("Ajax call complete, pretending result is good and submitting");
// All okay, go ahead and submit the form
rawFormElement.submit(); // Doesn't trigger 'submit' handler
}, 1500);
});
function display(msg) {
$("<p>").html(String(msg)).appendTo(document.body);
}
})();
</script>
</body>
</html>
回答by Arun P Johny
You can't prevent the default action from a success handler of ajax request because of the asynchronous nature of it.
由于它的异步性质,您无法阻止 ajax 请求的成功处理程序的默认操作。
Instead by default prevent the form submission, then in the success handler if it is valid then call the submit again.
相反,默认情况下阻止表单提交,然后在成功处理程序中,如果有效则再次调用提交。
$('.recover-form').on('submit', function (e) {
var form = $(this),
input = $('.check-recover-email'),
span = $('.recover-error'),
email = input.val();
span.text('');
//prevent the submit
e.preventDefault();
$.ajax({
url: 'ajax/check-email',
async: 'false',
cache: 'false',
type: 'POST',
data: form.serialize(),
success: function (response) {
if (response == 0) {
span.text('email does not exist');
} else {
//submit if valie
form[0].submit()
}
}
});
});
回答by Kevin B
First, you're options are incorrect. cache
and async
require boolean values, not strings.
首先,您的选项不正确。cache
并且async
需要布尔值,而不是字符串。
async: false,
cache: false,
Secondly, instead of submitting the form after the ajax request you're instead triggering the event. Try this instead.
其次,不是在 ajax 请求之后提交表单,而是触发事件。试试这个。
form.get(0).submit();
It returns the form node rather than a jquery object, allowing you to submit it directly rather than triggering an event (otherwise you would have an infinite loop.)
它返回表单节点而不是 jquery 对象,允许您直接提交它而不是触发事件(否则您将有一个无限循环。)
You don't really need async: false
or cache: false
in this case.
在这种情况下,您并不真正需要async: false
或cache: false
。
回答by Petar Vasilev
You need to do the following:
您需要执行以下操作:
$('.recover-form').on('submit', function(e){
e.preventDefault();
var form = $(this),
input = $('.check-recover-email'),
span = $('.recover-error'),
email = input.val();
span.text('');
$.ajax({
url: 'ajax/check-email',
async: 'false',
cache: 'false',
type: 'POST',
data: form.serialize(),
success: function(response){
if ( response == 0 ) {
span.text('email does not exist');
}
}
});
});
Notice how I've moved the e.preventDefault() to the beginning. This is because you were calling it when the ajax request responds which might happen 100s of milliseconds or even seconds after the form has been submitted
请注意我是如何将 e.preventDefault() 移到开头的。这是因为您在 ajax 请求响应时调用了它,这可能在表单提交后的 100 毫秒甚至几秒内发生
回答by Elias Soares
This happens because success function passed for jQuery.ajax()
is executed assyncly, then it will be executed after event handler function is finish.
发生这种情况是因为传递给的成功函数jQuery.ajax()
是异步执行的,然后它将在事件处理函数完成后执行。
You should put the e.preventDefault()
out of ajax function. and everything will work.
你应该把e.preventDefault()
ajax 函数去掉。一切都会好起来的。
回答by Dimag Kharab
Better you can try something like this ,
最好你可以尝试这样的事情,
<form name="myForm" onsubmit="return submitObj.validateAndSubmit();"> <!-- your form -->
<!-- your AJAX -->
var submitObj = {
validateAndSubmit : function()
{
var form = $('.recover-form'),
input = $('.check-recover-email'),
span = $('.recover-error'),
email = input.val();
span.text('');
$.ajax({
url: 'ajax/check-email',
async: 'false',
cache: 'false',
type: 'POST',
data: form.serialize(),
success: function(response){
if ( response == 0 ) {
return false;
}
else{
return true;
}
}
});
}
};