2011-08-19 58 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請求結束並返回「有效」變量之前就會返回。

相關問題