简体   繁体   中英

JavaScript continuing before function has finished!? Ajax asynchronous confusion and solution

I've got a problem. The function below works 100%, but the if statement which calls the function resolves before the function returns its result!

The alert for "test2" will show BEFORE the alert with the "result: "+data box does. What is the reason?

(The problem being that it ALWAYS resolves to false no matter what because nothing is returned even when something is going to be returned!)

    function checkUsername ( username ) {
        $.post("ajax_messages.php",{
            func: "checkUsername",
            username: username
        }, function(data){
            alert("result: "+data);
            return data;
        });
    }

    $('.send').click( function () {
        if ( checkUsername($receiverBox.val()) == "true" ) {
            alert("test");
            return false;
        } else {
            alert("test2");
            return false;
        }
    });

Edit:

Thanks for the swift replies. I tried the following:

    $.ajaxSetup({
        async:false
    });

Edit2: But this also did not act as expected. As a normal set of functions would so I will be expected to act. So I will be trying some more of the methods below

Edit3: Success! This is perfect. A little clumbsy but much much smoother than any other method I could find. I hope this helps

    var checkUsernameResult = false;

    function checkErrorCheckingIsComplete( ) {
        if ( checkUsernameResult != false ) {
            alert( checkUsernameResult );
        }
    }

    function checkUsername ( username ) {
        $.post("ajax_messages.php",{
            func: "checkUsername",
            username: username
        }, function(data){
            alert("result: "+data);
            checkUsernameResult = data; // each check has one of these
            checkErrorCheckingIsComplete(); // all checks have this as the end
        });
    }

    $('.send', $message_box).click( function () {
        checkUsername( $receiverBox.val() );
        //more checks here
        return false;
    });

Since AJAX calls are asynchronous this happens. Use a callback function for .post and put the if statement in that.

The other thing that you can do is to use synchronous calls.But this will stop the browser from executing any other action in the meantime.

我已经有几个月没有使用jQuery了,但是我很确定您可以设置一个标志来强制Ajax调用作为同步调用发生。

I think you might have to create another button that performs the submit, because you'll never have the response with Ajax's asynchronous functions.

Add another button to your HTML page with a class "actual-send", and then try this...

var asynchResult = "false";
function checkUsername ( username ) {
    $.post("ajax_messages.php",{
        func: "checkUsername",
        username: username
    }, function(data){
        alert("result: "+data);
        asynchResult = data;
        $('.actual-send').trigger('click');
    });
}

$('.send').click( function () {
    checkUsername($receiverBox.val())
    return false;
}
$('.actual-send').click( function () {
    if(asynchResult == "true") {
        alert("test");
        return true;
    } else {
        alert("test2");
        return false;
    }
}

As the other answers said, the post() method is asynchronous so it executes independently of the rest of the code.

If necessary you can force jquery to call the server synchronously using async:false instead, I think you'd have to use the jQuery.ajax() function instead of the .post() shorthand to do that though.

It generally works much better asynchronously though, as in synchronous mode it will freeze the webpage while it waits for the response from the server - not a great experience for your visitors. A better idea is to keep it in async mode and deal with the server response in the success() callback.

you can use following:

$.ajax({
  type: 'POST',
  url: 'ajax_messages.php',
  data: data,
  success: function(html){
   alert(html); 
  }
  dataType: dataType
});

so, on POST success execute function which grabs whatever your ajax_messages.php will echo and alerts with it

异步放置:false

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