2011-04-26 251 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"); 
}