2011-04-26 253 views
1

我有一個問題,當張貼一個驗證碼以驗證由php。 我的captcha_value串發送到captcha_check.php,我不知道該如何檢索返回值「真」或「假」jQuery ajax驗證captcha

$("#myForm").submit(function() { 
$.ajax({ 
     type: "POST", 
     url: '/captcha_check.php', 
     data: captcha_value 
     success: function(data) { 
      **?WHAT TO DO HERE? how to get true or false** 
     } 
}); 

captcha_check.php 
<?php 

if ($_POST['captcha'] == $_SESSION['captcha']) 
echo 'true'; 
else 
echo 'false'; 
?> 
+0

通過在成功回調函數中提供'alert(data)'來檢查它。 – Karthik 2011-04-26 10:29:59

回答

2

我設置標題爲XML輸出。

captcha_check.php

<?php 
header('Content-Type:text/xml');//needed to output as xml(that is my choice) 
echo "<root><message>"; 
if ($_POST['captcha'] == $_SESSION['captcha']) 
echo 'true'; 
else 
echo 'false'; 
echo "</message></root>"; 
?> 

$("#myForm").submit(function() { 
$.ajax({ 
     type: "POST", 
     url: '/captcha_check.php', 
     dataType:'xml', 
     data: captcha_value 
     success: function(data) { 
      if($(data).find('message').text() == "true"){ 
      //now you get the true. do whatever you want. even call a function 
      } 
      else{ 
     //and false 
      } 
     } 
}); 

這是我的解決方案可能是爲你的作品也。我總是喜歡用xml進行溝通。那是我的選擇。

+0

非常感謝你 – myro 2011-04-26 10:39:10

1
$.ajax({ 
    type: "POST", 
    url: '/captcha_check.php', 
    data: captcha_value, 
    dataType: "text", 
    success: function(data) { 
     if(data == "true") { 
      // correct 
     } else { 
      // nope 
     } 
    } 
}); 
1
dataType: 'json', //Important:Sometimes JQuery fails to automatically detect it for you. 
success: function(data) { 
    console.log(data ? "Data is true" : "Data is false"); 
}