jquery函数总是返回相同的

时间:2013-12-30 06:01:16

标签: javascript jquery

我的自定义javascript函数运行正常。但问题是它总是返回错误。

function uniqueChk()
{
    var flagV = false;
    jQuery.post("<?=base_url()?>index.php/authentication/chksid",
    { 
        sid: jQuery('#sid').val() 
    }, 
    function( data ) 
    {
        if(data == 'ok')
        {
            jQuery("#sid").removeClass("error");
            jQuery("#er_sid").html("");
            flagV = true;
        }
        else
        {
            jQuery("#sid").addClass("error");
            jQuery("#er_sid").html("This Student ID already in the database. Contact Admin if you have not done first time");
        }
    });
    return flagV;
}

如果我获得了data“ok”的值,则会从sid中删除类错误,但仍会返回false

2 个答案:

答案 0 :(得分:1)

尝试这样的事情

function uniqueChk()
{
    var flagV = false;
    $.ajax({
        type: 'POST',
        url: "<?=base_url()?>index.php/authentication/chksid",
        data: { sid: jQuery('#sid').val() },
        success: function(response){
          if(data == 'ok'){
                jQuery("#sid").removeClass("error");
                jQuery("#er_sid").html("");
                flagV = true;
          } else {
                jQuery("#sid").addClass("error");
                jQuery("#er_sid").html("This Student ID already in the database. Contact Admin if you have not done first time");
          }
        },
        async:false
    });
    return flagV;
}

默认情况下,所有请求都是异步发送的(默认情况下设置为true)。如果需要同步请求,请将此选项设置为false。

这意味着你的函数不会等待你的ajax响应完成。在你的ajax请求完成之前返回它的值。所以make ajax async

参考

http://api.jquery.com/jquery.ajax/

答案 1 :(得分:0)

因为你在ajax之前返回的函数有机会回来。这是异步功能的正常行为。那时请查看$ .deferred。

相关问题