jQuery check returns undefined

2019-03-05 11:00发布

My experience in jQuery is limited and I've searched around for an answer but can't seem to find it.

This function returns a false or true based on a get. Now my problem is that the function 'Availability' doesn't return a false nor true if I get my data.

This is the code.

function Availability(){
    var email = jQuery('#emailRegister').val();
      jQuery.get("test.php", {email: email})
        .done(function(data) {
          if(data == 'true'){
            jQuery(".warningEmailDuplicate").hide();
            return true;
          }else if(data == 'false'){
            jQuery(".warningEmailDuplicate").show();
            return false;
        }
    });
}

2条回答
姐就是有狂的资本
2楼-- · 2019-03-05 11:50

jQuery.get creates an AJAX request. These are asynchronous. You cannot return a value from the AJAX callback to the calling function. The function will have exited, returning nothing, before the HTTP request completes.

You need to rewrite your code to use callbacks:

function Availability(){
    var email = jQuery('#emailRegister').val();
      jQuery.get("test.php", {email: email})
        .done(function(data) {
          if(data == 'true'){
            jQuery(".warningEmailDuplicate").hide();
            AvailabilityResult(true);
          }else if(data == 'false'){
            jQuery(".warningEmailDuplicate").show();
            AvailabilityResult(false);
        }
    });
}

function AvailabilityResult(available) {
    // *available* will be true or false
    // do with this value what you wanted to do with the return value from Availability
}
查看更多
爷的心禁止访问
3楼-- · 2019-03-05 11:54

JQuery is Async scripting language, so when you calls this method compiler does not wait to get the return value.

When you call Availablity(); then off-course an Ajax get request sends to test.php and in the mean time compiler returns nothing from your method and assign variable seems undefined.

To prevent this issue, you need to create a callback function rather than simple return the value. see example with no callback and example with callback

Try this code:

function Availability(callback){
    var email = jQuery('#emailRegister').val();
      jQuery.get("test.php", {email: email})
        .done(function(data) {
          if(data == 'true'){
            jQuery(".warningEmailDuplicate").hide();
            callback(true);
          }else if(data == 'false'){
            jQuery(".warningEmailDuplicate").show();
            callback(false);
        }
    });
}
//calling function
Availablity(function(status){
var available = status;
    alert(available);
});
查看更多
登录 后发表回答