简体   繁体   中英

Return false doesn't stop the code in ajax $.post

I execute an ajax request using $.post , this is my code:

$.post(postUrl, postData, function(response)
{
      if(response.status == "SUCCESS")
      {
             updateConfirmFrame();
      }
      else
      {
             return false;
      }
 }, 'json');

now if the response return SUCCESS the code continue calling a function that unlock some control, but if an exception is handled, so the code should blocked. Now I've put an alert in return false; condition and the alert is printed correctly but, the return false doesn't stop the code. I don't want that the code continue the execution. I also tried with throw Exception but doesn't working. What am I doing wrong?

UPDATE

$.post(postUrl, postData)

.done(function(response)
{
    if(response.status == "SUCCESS")
    {
        updateConfirmFrame();
    }
    else
    {
            alert("error"); //The problem is here
            return false;
     }
 })
 .fail(function(err)
 {
       return false;
 });

alert("hi wor")

Use that:

$.post(url, postdata)
 .done(function(response) {

  })
 .fail(function(err) {
   // error
 });

The syntax you used is $.post(postUrl, postData, success_callback, fail_callback);

return statements only return the function they are within, stopping further code execution in that function . They do not stop JS code execution in general.

The alert statement you are saying shouldn't run because you've done return false; is not in the function returning false. It would not be affected by the fact that some other function returned false. It absolutely should run.


On top of that, the success function for your post call is an event callback. It is created, but does not run until the actual loading of the file happens, which is gonna be long after other code outside your ajax stuff finishes. So the code in that function isn't even gonna be executing before that alert takes place.

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