【问题标题】:jQuery ajax validate captchajQuery ajax 验证验证码
【发布时间】:2023-11-25 19:53:02
【问题描述】:

我在发布验证码以通过 php 验证时遇到问题。 我将captcha_value 字符串发送到captcha_check.php,但我不知道如何检索返回值'true' 或'false'

$("#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';
?>

【问题讨论】:

  • 通过在成功回调函数中给出'alert(data)'来检查它。

标签: php jquery ajax captcha


【解决方案1】:

我将标头设置为输出为 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 进行通信。那是我的选择。

【讨论】:

    【解决方案2】:
    $.ajax({
        type: "POST",
        url: '/captcha_check.php',
        data: captcha_value,
        dataType: "text",
        success: function(data) {
            if(data == "true") {
                // correct
            } else {
                // nope
            }
        }
    });
    

    【讨论】:

      【解决方案3】:
      dataType: 'json', //Important:Sometimes JQuery fails to automatically detect it for you.
      success: function(data) {
          console.log(data ? "Data is true" : "Data is false");
      }
      

      【讨论】: