简体   繁体   中英

How to stop in jquery $.post?

i want to stop executing javascript code after the line "return false",but it don't.

my english is poor. if anyone understand me,please improve my question thank you!

    $('#category-list input').blur(function(){
        var $$ = $(this), $p = $$.prev();
        if ($$.val() != $p.html()) {
            var data = {'key':$$.attr('name'),'value':$$.val()};
            $.post('<?php echo Url::to(['field']); ?>', data).done(function(result){
                if (result != 'ok'){
                    alert(result);
                    return false; /*i need it stop at here!!!!!! but it not*/
                }
            });
            alert(3);
            $p.html($$.val());
        }
        $$.hide();
        $p.show();
    });

The short answer is you can't stop a parent function inside an ajax completion function because that will most likely fire after the function itself is finished executing. Regardless, its 2 separate events

$.post is an asynchronous ajax request. This means, that the .done() part of the function will execute AFTER the ajax request comes back.

However, the rest of the function runs synchronously, meaning every (or some) line of code after .post will run before the server even responds. To get around this, you need to re-architect how you execute your functions.

let's examine this with a basic function:

function getSomeAjax() {
  //1 - the alert will execute first
  alert('first line of execution');
  //2 - the post request will execute second
  $.post('someUrl', data).done(function(result){
     if (result != 'ok'){
       alert('post request complete');
       //this will execute randomly whenever the server responds. 
       //it could be in 1 second, 5 seconds, or 20 seconds
     }
  });
  //3
  alert('last line of execution');
}

looking at the example above, you should move any logic that is dependent on the server response into the if clause. Otherwise it will execute regardless of your post request

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM