2012-05-02 36 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'); 
     } 
    } 
}) 

...