2014-03-03 93 views
1

我有一個switch語句返回true或false,並且if和else語句然後用它來做更多的驗證。獲取Json返回true或false

因爲該值使用ajax在輸入字段上發送。我希望PHP返回true或false。

我已經嘗試使用JSON,我使用警報來測試我回來了,它只是很多的HTML。

$a = isset($_POST['ccode']) ? $_POST['ccode'] : NULL; 

    function isValid($Code) { 
     switch ($Code){ 
      case "123": 
      case "45545": 
      return true; 
     default: 
      return false; 
     } 
    } 

if(isValid($a)) { 
     $correct = "correct"; 
     echo json_decode($correct); 
    } 
    else { 
     $incorrect = "incorrect"; 
     echo json_decode($incorrect); 
    } 

AJAX

$('#ccode').blur(function() { 
    var code = $(this).val(); 

    $.ajax({ 
     type:'POST', 
      url: 'index.php', 
      dataType: 'json', 
      data:{ 
      ccode:code 
      }, 
      success: function(data) { 
      alert(data); 
      } 
    }); 

當你看到警報(數據) 我將與

if (data == false) { 
//do this 
} 

}); 

來代替它我的代碼不會返回true或false從PHP和警報它只是從我的索引頁面輸出大量的HTML。

我做錯了什麼?

+1

爲什麼回顯json_decode?它應該是json_encode –

+0

@abbiya謝謝,但我的'如果(數據== true)'不起作用。 – user3057514

回答

3

您的輸出不是truefalse而是"correct""incorrect"

如果你使用這些值比較data你可能會得到更好的結果:

if (data === "correct") { 
    // correct 
} else { 
    // incorrect 
} 

哦,是啊,你正在使用json_decode代替json_encode

+0

嗨,謝謝但我的if語句不起作用 – user3057514

+0

嗨,對不起,_「不起作用」_不是我可以使用的描述。 – Halcyon

+0

請看看我的問題編輯部分多數民衆贊成 – user3057514

0

在你的PHP

echo json_decode($incorrect); 

替換爲

echo json_enecode(array("success"=>$incorrect)); 

然後在JavaScript解析這個JSON。

0

在你的PHP

echo json_decode($incorrect); 

替換爲

echo json_encode(array("error"=>false, "message"=>$incorrect)); 

然後在JavaScript解析這個JSON。

,做這樣的jQuery的

if (data.error == false) { 
//do this 
} 
+0

沒有工作是所有的HTML代碼 – user3057514

+0

那些是什麼。郵寄 –

0

你$正確的變量應該是這樣的

$correct = ['isValid'=> true] 

一個數組,那麼你編碼

在你成功的jQuery的回調函數,你可以調試它來檢查結果值

alert(data.isValid)