use jquery ajax don't have callback when retur

2019-09-05 21:29发布

问题:

I try use query ajax and when I have "return false" I get callback as well

$(document).ready(function(){

    $("form#Form").submit(function(){
        $.ajax({
            url: "ajax.php",
            type: "POST", 
            data: $(this).serialize(), 
            success: function(callback){ 
                alert(callback);            
            } //success
        }); //ajax

        return false;

    }); //submit
}); //ready

in the php file I just echo "dennis", it works and I get alert with content "dennis". when I try something like this:

$(document).ready(function(){

    $("form#Form").submit(function(){
        $.ajax({
            url: "ajax.php",
            type: "POST", 
            data: $(this).serialize(), 
            success: function(callback){ 
                alert(callback);            
            } //success
        }); //ajax

    if (callback == "dennis"){
        return false;
    }else{
        return true;
    }   

    }); //submit
}); //ready

I get empty alert and the form act like he get "return true". I also try put variable and return him, but still same problem..

why it happened? how fix it?

回答1:

This is because the ajax-scope will execute asynchronous, hence when you check if (callback == "dennis"), you ajax call may not even reached your php yet, therefore callback will be undefined.

You need to check callback (it's actually a bad variable name as it is not a callback, but a result from your ajax-call) in the success scope.

$.ajax({
    url: "ajax.php",
    type: "POST", 
    data: $(this).serialize(), 
    success: function(callback){ 
       alert(callback);
       if (callback == 'dennis') {
           return true;
       } else return false;
    } //success
}); //ajax

Now, your next problem is that your form probably already returns true, so better calling a new function with your result, than returning true|false here.

 // ajax metod success function
    success: function(result){ 
       alert(callback);
       onFormReturn(result);
    } //success

and define the function to handle result

// elsewhere, outside ajax-scope - even outside document.ready
function onFormReturn(result) {
   if (result == "dennis") {
      // do your stuff
   } else {
      // do something else
   }
}


回答2:

See my first comment on your question, thats why its not working.

You could do something like this, but i don't recommend it:

var foo = null;

$.ajax({
    url: '/',
    method: 'POST',
    async: false,
    success: function(result) {
        foo = result;
    }
});

// use foo