返回 False 在 jQuery.ajax 中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9422215/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:47:40  来源:igfitidea点击:

Return False not working inside jQuery.ajax

jqueryajax

提问by Gilberto Albino

P.S.: Read "EDITED on 2019-06-29":

PS:阅读“于 2019-06-29 编辑”:

I have a webform for updating user information, and when he updates his email a verification is performed via ajax()so that he is warned if the new email address is already in use by another user.

我有一个用于更新用户信息的网络表单,当他更新他的电子邮件时,会执行验证,ajax()以便在新电子邮件地址已被其他用户使用时向他发出警告。

I'm trying to cancel the form submission when the email is in use, but return false;doesn't work.

我试图在电子邮件正在使用时取消表单提交,但return false;不起作用。

Any other return false;within if statements are working fine, the problem is only with this one inside the jQuery.ajax()call.

return false;if 语句中的任何其他语句都可以正常工作,问题仅在于jQuery.ajax()调用中的这个语句。

Here's the actual code:

这是实际的代码:

var email = jQuery('#email').val();
jQuery.ajax({
    type : 'GET',
    url : '/ajax/verify-email.php?email=' + email,
    success : function( d ) {
        if( d == '1' ) {
            alert('Another user is using this email');
            jQuery('input[name="email"]').focus();
            return false; // this guy over here is not working!!!!
        }
    }
});

Does anyone have a solution?

有没有人有办法解决吗?

EDITED on 2019-06-29

编辑于 2019-06-29

When I asked this question back in 2012 I wasn't aware of Promises in Javascript, neither knew about "$.when" (even though added 3 years later of this question) to handle asynchronous requests alongside $.ajax.

当我在 2012 年问这个问题时,我不知道 Javascript 中的 Promises,也不知道“$.when”(尽管这个问题是在 3 年后添加的)与 $.ajax 一起处理异步请求。

Today, you can handle the same scenario easily, as this:

今天,您可以轻松处理相同的场景,如下所示:

let email = $('#email').val();
$.when(
  $.ajax({
    type : 'GET',
    url : `/ajax/verify-email.php?email=${email}` 
  })
 .then(function(d) {
   alert('Another user is using this email');
   $('input[name="email"]').focus();
});
// your code continues from here as desired...

回答by Darin Dimitrov

The A in AJAX is actually very important. It stands for Asynchronous. This means that you trigger a request to the server which might take some time to process and you get a response later. This response happens inside the success callback. But since this happens much later than the actual form submission, your form has actually been already submitted before the response comes back. So returning false from an AJAX success callback makes no sense whatsoever. What you want to do is to return false from the submit handler of your form. Let's see how we could implement this.

AJAX 中的 A 实际上非常重要。它代表异步。这意味着您触发了对服务器的请求,该请求可能需要一些时间来处理,然后您会得到响应。此响应发生在成功回调中。但是由于这比实际的表单提交晚得多,因此您的表单实际上已经在响应返回之前提交了。所以从 AJAX 成功回调返回 false 没有任何意义。您想要做的是从表单的提交处理程序返回 false。让我们看看我们如何实现这一点。

You could subscribe to the .submithandler of the form and send an AJAX request to verify whether the email has already been taken or not and if it is not taken manually trigger the submission of the form inside the success AJAX callback:

您可以订阅.submit表单的处理程序并发送 AJAX 请求以验证电子邮件是否已被接受,如果没有被手动触发,则在成功的 AJAX 回调中触发表单的提交:

$('form').submit(function() {
    // we send an AJAX request to validate the unicity of the email
    $.ajax({
        url: '/ajax/verify-email.php',
        type: 'POST',
        data: { email: $('#email').val() },
        // we set the context to the form so that inside
        // the success callback 'this' points to the form
        context: this,
        success: function(result) {
            if (result != '1') {
                // If the server send something different than 1
                // we know that the email is unique and trigger
                // the submission of the form using the underlying
                // DOM element to avoid calling the .submit handler
                // recusrively
                this.submit();
            } else {
                // The email is not unique => we are informing
                // the user that the email is already in use
                alert('Another user is using this email');
                $('#email').focus();
            } 
        }
    });

    // we cancel the normal submission of the form    
    return false;
});

Also never rely on client side validation. Make sure that you are performing the email is uniquecheck once the form has been successfully submitted to the server. If you are using a SQL database that's easily achieved with a unique constraint on your Email field.

也永远不要依赖客户端验证。email is unique一旦表单成功提交到服务器,请确保您正在执行检查。如果您使用的 SQL 数据库可以通过电子邮件字段的唯一约束轻松实现。

回答by Javier Pérez Batista

You should not use .submit()on this situation, use a flag system instead, .submit()should only be used for <form>elements.

你不应该.submit()在这种情况下使用,而是使用标志系统,.submit()应该只用于<form>元素。

var email = jQuery('#email').val();
var flag = 0;
jQuery.ajax({
    type : 'GET',
    url : '/ajax/verify-email.php?email=' + email,
    async: false,
    success : function( d ) {
        if( d == '1' ) {
            alert('Another user is using this email');
            jQuery('input[name="email"]').focus();
            flag = 1;
        }
    }
});
if(flag == 1) return false;

回答by harsha

<form action="yourpage" method="post" onsubmit="return matchpass();">
  <div>
   <label> Name</label>
   <input type="text" name="name" id="name">
  </div>
  <div>
   <label> Email ID</label>
   <input type="email" name="email" id="email">            
  </div>
  <div>
   <label> Mobile No</label>
   <input type="text" name="mob"  maxlength="10" onkeyup="check_if_exists();" autocomplete="off" id="mob">
  </div>                             
  <div>
   <button type="button" >Send</button>
  </div>
  <span id="err"></span>
  <div>
   <label> OTP</label>
   <input type="password" name="otp" id="otp"  maxlength="6" placeholder="****">
   <span id="err2"></span>
  </div>    
  <div>
   <input type="reset" value="Reset" class="reset-btn">
   <input type="submit" name="submit" id="submit" value="Submit" >              
  </div>
</form>
<input type="hidden"  id="otpcheck"/>



<script>
function matchpass()
{

     $.ajax({   
    type:"post",
    url: "yourpage",
    data:{ mobile:mob,otp:otp},
    success:function(data)
    {
       if(data==1)
       {
           document.getElementById("otpcheck").value=1; //important
       }else{

           document.getElementById("err2").style.color = "red";
           document.getElementById("err2").innerHTML = "invalid OTP Number ";
         document.getElementById("otpcheck").value=0; //important
       }


    }
    });

    if(document.getElementById("otpcheck").value==0){
        return false;
    }

}

回答by user11713679

$('form').submit(function() {
// we send an AJAX request to validate the unicity of the email
$.ajax({
    url: '/ajax/verify-email.php',
    type: 'POST',
    data: { email: $('#email').val() },
    // we set the context to the form so that inside
    // the success callback 'this' points to the form
    context: this,
    success: function(result) {
        if (result != '1') {
            // If the server send something different than 1
            // we know that the email is unique and trigger
            // the submission of the form using the underlying
            // DOM element to avoid calling the .submit handler
            // recusrively
            this.submit();
        } else {
            // The email is not unique => we are informing
            // the user that the email is already in use
            alert('Another user is using this email');
            $('#email').focus();
        } 
    }
});

// we cancel the normal submission of the form    
return false;

});

});

回答by Nit_dash

you should use event.preventDefault() as shown below.

您应该使用 event.preventDefault() ,如下所示。

$('#form').submit(function(event) {
    $.get('/ajax/verify-email.php?email=' + $('#email').val(), function(d) {
        if (d == '1') {
            alert('Another user is using this email');
            $('#email').focus();
            event.preventDefault();
        }
    });   
});

回答by Christoph

You run async code here. At the moment you are trying to return false, it is far to late. Your function already returned undefined. You need to provide a callback if you want to process the result of your success.

您在此处运行异步代码。目前您正试图返回 false,为时已晚。您的函数已经返回undefined。如果要处理成功的结果,则需要提供回调。

回答by Thew

Seems like you don't realy get the idea jQuery. You don't need to use return false, and not there. You can call event.preventDefault();:

似乎您并没有真正了解 jQuery。你不需要使用 return false,而不是那里。您可以致电event.preventDefault();

$('#form').submit(function(event) {
    $.get('/ajax/verify-email.php?email=' + $('#email').val(), function(d) {
        if (d == '1') {
            alert('Another user is using this email');
            $('#email').focus();
        }
    });

    event.preventDefault();
});

See this example.

请参阅此示例