2012-08-16 17 views
0

我正在爲我的電子郵件表單構建一個簡單的抗體。 這使得問題的代碼:使用PHP和JQuery AJAX的Antibot

<?php 
    session_start(); 
    $a = rand(1, 10); 
    $b = rand(1, 10); 
    $antibot = $a + $b; 
    $_SESSION["antibot"] = $antibot; 
?> 
<html> 
<head> 
<script src="http://code.jquery.com/jquery-latest.js"></script> 
<script> 
$(document).ready(function(){ 
    $("#sendEmail").click(function(){ 
      var antibot = $("#antibot").val(); 
     $.post(
      "test.php", 
      {antibot: antibot}, 
      function(data){ 
        alert(data.info); 
      }, 
      "json" 
      ); 
     ); 
    ); 
); 
    </script> 
    </head> 
    <body> 
    <table> 
     <tr><td>AntiBot: <?php echo $a . ' + ' . $b;?> = </td><td><input type='text' id='antibot' /></td></tr> 
     <tr><td colspan='2'><input type='button' id='sendEmail' value='Send'/></td></tr> 
    </table> 
    </body> 
    </html> 

我的test.php的

<?php 
    session_start(); 
    $antibot = $_POST["antibot"]; 
    $data = array(); 
    if(isset($_SESSION["antibot"])){ 
     if($_SESSION["antibot"] == $antibot){ 
      $data["info"] = "Session is isset and answer is right!"; 
     } 
     else{ 
      $data["info"] = "Session is isset but answer is NOT right!"; 
     } 
    } 
    else{ 
     $data["info"] = "Session is NOT isset!"; 
    } 
    echo json_encode($data); 
?> 

我不斷地得到這個信息:「會議是isset,但答案是不正確的」 如果你可以看到test.php中的$ _SESSION [「antibot」]被設置,但是無論我在輸入字段#antibot中輸入了什麼,值都是""

我不明白爲什麼會發生這種情況,請有人告訴我問題在哪裏,我該如何解決?

+0

你不應該檢查isset($ antibot)嗎? – MimiEAM 2012-08-16 05:51:18

+0

沒關係。我查了好多次,唯一的問題是$ _SESSION [「antibot」]有一個空白值。 – consigliere 2012-08-16 05:53:00

+0

我已經通過您的代碼,這是我首先理解您生成兩個隨機數字並總結它並將它保存爲會話中的抗體。然後在表單中,用戶在抗體字段中輸入一些值。當用戶提交的頁面值被髮送到test.php並且在test.php中,您正在匹配會話值和用戶輸入的抗體值。那是對的嗎 ? – Nick 2012-08-16 05:58:51

回答

1

我測試了這個代碼在這裏: http://onlinephpfunctions.com/stackoverflow/11981309/

而且似乎完全有效的。

我不得不做出一些修改您的JavaScript:

<script type="text/javascript"> 
$(document).ready(function(){ 
    $("#sendEmail").click(function(){ 
      var antibot = $("#antibot").val(); 
     $.post(
      "test.php", 
      {antibot: antibot}, 
      function(data){ 
       alert(data.info); 
      }, 
      "json" 
      ) 
    }) 

}) 
    </script> 

,這是工作的罰款後。這可能只是在瀏覽器中存在一些Cookie問題,或者在PHP配置中存在錯誤,因此會話不會正確存儲。請檢查這一點,你的代碼工作正常,你可以在演示中看到。

+0

謝謝,我嘗試了鉻,IE瀏覽器,FF和存在的問題,所以問題是服務器?但是這很奇怪,因爲當我在index.php上回顯$ _SESSION [「antibot」]時,我得到了正確的值,但問題出在mail.php上,它不會在我的服務器上工作,我將寫入主機支持。 – consigliere 2012-08-16 06:08:18

+0

你應該使用兩個文件來檢查它。在第一個文件中設置會話變量,在第二個文件中回顯它。如果第二個文件沒有返回變量,則說明有問題。也可以肯定test.php是在同一臺服務器上,並在同一個帳戶... – 2012-08-16 06:13:38

+0

好的,我會嘗試,test.php是在同一臺服務器和帳戶.. – consigliere 2012-08-16 06:14:38