2011-08-19 66 views
1
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())为真,结果警报始终为false 控件在此如何传递。 thnks ..函数返回false甚至条件为真为什么?

回答

1

如果你的“得到” 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 
    }); 

} 
+1

这从同一个问题,因为OP的代码受到影响。 'callback'需要在$ .get后面调用。 –

+0

好点火箭,我刚刚编辑...谢谢!似乎我需要更多的光线。 –

+0

我怎样才能得到checkform1以外的结果,但在checkform内部,以便我可以将它返回给提交者,thnks。 – Irfan

1

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

0

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

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

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; 

} 
2

内默认情况下$不用彷徨又名Ajax.get是异步的(它运行在后台)。所以你的函数“checkform1”在Ajax请求结束并返回“有效”变量之前就会返回。

相关问题