2012-05-02 38 views
0

在jquery ajax函數中,我收回服務器的「真」或「假」字符串。然後我只知道結果,但只有在條件不成立的情況下。在javascript中比較字符串

$.ajax({ 
    ... 
     success: function(result) { 
       if(result == "true"){ // false??????? 
        alert('true'); 
       } else { 
        alert('false'); 
       } 
      } 
     }) 
    ... 

$.ajax({ 
... 
    success: function(result) { 
      var result2 = String(result); 
      alert(result2);   // true 
      alert(typeof result2); // String 
      alert(typeof "true"); // String 
      if(result2 == "true"){ // false??????? 
       alert('true'); 
      } else { 
       alert('false'); 
      } 
     } 
    }) 
... 

...

有人能幫助我嗎?

+1

如果你的解釋說'result =='true''是'false',那麼'result'不是''true''。就這麼簡單。你可能想要檢查你是否假設'結果是,真的在持有。嘗試'console.log(result)'。 – Yoshi

+0

您確定結果中包含「true」嗎? –

+0

您正在使用jQuery,而jQuery有時使用「智能猜測」來計算結果類型。試試'result === true'。它可能已變成布爾型。 – Joseph

回答

5

有可能是換行或多餘的空格「結果」。

+0

獎勵你!我只在JS中尋找問題,但我使用println()函數,而不是print()來響應java servlet。 – Dani

0

嗯,

空字符串,NULL,0和undefined都是假的

result2==="true"是一個更好的測試

DEMO

0

使用TRIM()函數...

如:

$阿賈克斯({

...

success: function(result) { 
     var result2 = String(result.trim()); 
     alert(result2);   // true 
     alert(typeof result2); // String 
     alert(typeof "true"); // String 
     if(result2 == "true"){ // true 
      alert('true'); 
     } else { 
      alert('false'); 
     } 
    } 
}) 

...