jQuery 检查返回未定义 [英] jQuery check returns undefined

查看:27
本文介绍了jQuery 检查返回未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 jQuery 方面的经验有限,我四处寻找答案,但似乎找不到.

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

此函数根据 get 返回 false 或 true.现在我的问题是,如果我获得数据,可用性"函数不会返回 false 或 true.

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.

这是代码.

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;
        }
    });
}

推荐答案

jQuery.get 创建一个 AJAX 请求.这些是异步的.您不能将 AJAX 回调中的值return 给调用函数.在 HTTP 请求完成之前,该函数将退出,不返回任何内容.

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
}

这篇关于jQuery 检查返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆