即使条件为真,函数返回false也是如此?

时间:2011-08-19 13:05:59

标签: javascript

function checkform(for1)
{ 
   var result=checkform1(for1);
   alert(result);
}
function checkform1(form)
{
    var valid=false;
    var val1 = document.getElementById('security_code').value;
    $.get(url, function(data) {
        if(data.toString()==val1.toString())
        {
            var elem = document.getElementById("captchaerr");
            elem.style.visibility = 'hidden';
            valid=true;
        }
        else
        {
            var elem = document.getElementById("captchaerr");
            elem.style.visibility = 'visible';
            valid=false;
        }           
    }); 
    return valid;
}
即使condtion(data.toString()== val1.toString())为true,

结果警告始终为false 控制如何通过这个。 thnks ..

5 个答案:

答案 0 :(得分:2)

默认情况下,$ .get aka Ajax.get是异步的(它在后台运行)。所以你的函数“checkform1”在Ajax请求完成之前返回并设置“valid”变量。

答案 1 :(得分:1)

不要使用toString()作为字符串。toString()将返回string。只需测试data == val1

答案 2 :(得分:1)

您正在进行异步调用,因此如果要检查结果,则必须在回调中执行此操作

 function checkform1(form)
{
    var valid=false;
    var val1 = document.getElementById('security_code').value;
    $.get(url, function(data) {
        if(data.toString()==val1.toString())
        {
        var elem = document.getElementById("captchaerr");
        elem.style.visibility = 'hidden';
        valid=true;
        }
        else
        {
        var elem = document.getElementById("captchaerr");
        elem.style.visibility = 'visible';
        valid=false;
        }      
        //here you will get the valid and 
        //not outside...outside it will be always false.
    }); 

    //This line will be executed immediately after the previous line
    // and will not wait for the call to complete, so this needs to be done 
    // in the callback. 
    return valid;

}

答案 3 :(得分:1)

如果你的'get'ajax调用是异步调用,你可以使用回调来获得结果:

function checkform(for1)
{ 
   checkform1(for1, function(result) //provide the callback to the async function
   {
     alert(result); 
   });      
}
function checkform1(form, callback)
{
    var valid=false;
    var val1 = document.getElementById('security_code').value;
    $.get(url, function(data) 
    {
        if(data.toString()==val1.toString())
        {
            var elem = document.getElementById("captchaerr");
            elem.style.visibility = 'hidden';
            valid=true;
        }
        else
        {
            var elem = document.getElementById("captchaerr");
            elem.style.visibility = 'visible';
            valid=false;
        }           
        if(callback)
            callback(valid);// call the callback INSIDE of the complete callback of the 'get' jquery function
    }); 

}

答案 4 :(得分:0)

就在条件将警报放在两个值alert(val1 +'---'+ data)之前,看它是否完全相同。

在比较前修剪它们,以防万一它有一些填充。