2015-12-09 69 views
0

所以,我一直在測試,結果發現,如果如何獲得處理AJAX函數以返回布爾值的PHP函數?

session_start(); 
if ($_POST['animal'] != $_SESSION['animal']) die(json_encode(false)); 

是我的PHP函數來處理AJAX調用,然後再在JavaScript的土地上,我有

 success: function (correctCaptcha) { 
      console.log("correctCaptcha is " + correctCaptcha); // test 
      console.log("correctCaptcha's type is " + typeof (correctCaptcha)); // test 
       if (correctCaptcha) 
       { 

我在裏面運行看到correctCaptcha是字符串「false」而不是布爾值false。因此,輸入if塊,這就是導致錯誤的原因。我如何讓PHP給我一個布爾值,就像它生成的JSON一樣?或者什麼是更好的解決方案?

+2

簡單的解決辦法是'如果(correctCaptcha ==「假」)' – RiggsFolly

+0

@RiggsFolly很明顯,但我不希望對這個網站的編碼進行太多的操縱 –

回答

2

你可以做

json_encode((bool)1); // which is true 

或者

json_encode((bool)0); // which is false 

理想的情況下,雖然你會想要做這樣的事情

$results = ["result" => false]; 
json_encode($results); 

從文檔,這應該保留布爾值,不轉換爲字符串。

然後訪問您的JavaScript這樣的結果(作爲一個對象)

console.log(correctCaptcha.result);