2016-01-01 74 views
1

我在我的網站中一起使用PHP和AJAX從JSON URL中獲取數據並將其顯示在網頁上。當我在不使用recaptcha的情況下使用它時,它運行良好,但是當我整合Google的Recaptcha時,只有當驗證碼拼圖每次解決兩次時,結果纔會顯示。我不確定這個bug究竟在哪裏,我甚至試圖實現一個自定義驗證碼,在這種情況下它也是一樣的。下面是驗證碼代碼,與Recaptcha一起使用時,Ajax調用無法正常工作

驗證碼和Ajax代碼片段:

<?php 
if ($resp != null && $resp->success): ?> 

echo"hi"; 

<script> 
$(document).ready(function(){ 

$("#submit").click(function(){ 

$.post("retrieve_train_between_stations.php", $("#get_train_running").serialize(), function(response) { 
$("#success").html(response); 


}); 
return false; 


}); 

}); 
</script> 


<?php 
else: 
echo "Failed"; 

?> 

全碼: http://pastebin.com/UynEiYng

+0

鑑於你的腳本,這是預期的行爲。 – frz3993

+0

我哪裏錯了?有沒有解決這個問題的方法? @ frz3993 –

+0

腳本'$ _POST'的第一個負載不存在,所以'$ resp'將爲false,並且腳本部分不存在。在第一次提交時,將會填充'$ _POST'並且'$ resp'將成爲true,腳本部分就會出現。只有在第二次提交時腳本纔有效。 – frz3993

回答

1

這部分應該移到retrieve_train_between_stations.php

require_once "recaptchalib.php"; 
// your secret key 
$secret = "My secret key"; 
// check secret key 
$reCaptcha = new ReCaptcha($secret); 

$resp = false; 

if (isset($_POST["g-recaptcha-response"])) { 
    $resp = $reCaptcha->verifyResponse(
     $_SERVER["REMOTE_ADDR"], 
     $_POST["g-recaptcha-response"] 
    ); 
} 

if ($resp) { 
    //display the record 
} else { 
    echo 'Recaptcha can not be verified.'; 
} 

的if/else語句應該被刪除,防止默認事件爲腳本

<script> 
$(document).ready(function(){ 

$("#submit").click(function(event){ 
    event.preventDefault(); 
    $.post("retrieve_train_between_stations.php", $("#get_train_running").serialize(), function(response) { 
$("#success").html(response); 


     }); 
     return false; 

    }); 

}); 
</script> 
+0

我會嘗試這一個,並會通知你它是否有效。 –

+0

我的確如此:http://pastebin.com/vBE5UF3G 但現在它不給我回結果。 –

+1

我可以看到你正在嘗試在函數上下文中使用'$ resp'。您需要將它作爲參數傳遞給函數,或者使用'$ _GLOBAL',以便在函數上下文中使用它。在函數環境中,'$ resp'將不被聲明。 – frz3993