0
我有一個評論表單,它使用ajax顯示評論框使用彈出菜單,並提交評論時,註釋被註冊到適當的職位(沒有任何頁面刷新)。我想添加驗證碼到這個表單。captcha驗證在php中使用javascript
我試着實現下面的JavaScript代碼,它生成一個小的隨機數captcha。
<p>
<label for="code">Write code below > <span id="txtCaptchaDiv" style="color:#F00"></span><!-- this is where the script will place the generated code -->
<input type="hidden" id="txtCaptcha" /></label><!-- this is where the script will place a copy of the code for validation: this is a hidden field -->
<input type="text" name="txtInput" id="txtInput" size="30" />
</p>
上面的html用於顯示生成的驗證碼和用戶輸入代碼的文本輸入。
以下是JavaScript代碼生成的代碼 -
<script type="text/javascript">
//Generates the captcha function
var a = Math.ceil(Math.random() * 9)+ '';
var b = Math.ceil(Math.random() * 9)+ '';
var c = Math.ceil(Math.random() * 9)+ '';
var d = Math.ceil(Math.random() * 9)+ '';
var e = Math.ceil(Math.random() * 9)+ '';
var code = a + b + c + d + e;
document.getElementById("txtCaptcha").value = code;
document.getElementById("txtCaptchaDiv").innerHTML = code;
</script>
下JavaScript代碼被用於驗證碼的驗證 -
<script type="text/javascript">
function checkform(theform){
var why = "";
if(theform.txtInput.value == ""){
why += "- Security code should not be empty.\n";
}
if(theform.txtInput.value != ""){
if(ValidCaptcha(theform.txtInput.value) == false){
why += "- Security code did not match.\n";
}
}
if(why != ""){
alert(why);
return false;
}
}
// Validate the Entered input aganist the generated security code function
function ValidCaptcha(){
var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
var str2 = removeSpaces(document.getElementById('txtInput').value);
if (str1 == str2){
return true;
}else{
return false;
}
}
// Remove the spaces from the entered and generated code
function removeSpaces(string){
return string.split(' ').join('');
}
</script>
此代碼的工作正常時不與所述組合評論表格。結合評論表單,驗證沒有完成。
對於基於ajax的評論表單,提交按鈕傳遞一個隱藏的輸入變量來提交與相應的帖子相關的評論。 這是提交按鈕代碼爲我的評論部分 -
<button type="submit" class="comment-submit btn submit" id="submitted" name="submitted" value="submitted"><?php _e('Submit', APP_TD); ?></button>
<input type='hidden' name='comment_post_ID' value='<?php echo $post->ID; ?>' id='comment_post_ID' />
所以基本上我想我的代碼首先檢查驗證碼值上提交評論表單的按鈕,如果它的正確我想用提交評論僅限ajax功能。
您目前的創建和驗證CAPTCHA的策略是一個壞主意, [這裏](http://stackoverflow.com/questions/8987511/simple-javascript-captcha-using-random-array) - 爲您的CAPTCHA有用於固定網頁的任何一點,你將不得不生成它的服務器上並不與客戶分享解決方案。您可以通過將txtCaptcha中的值複製到txtInput中來輕鬆破解。 –
哦,這就是實際上,所以我想我已經建立了一個更安全的驗證碼使用PHP本身。在PHP –
化妝驗證碼分配給會話,這樣你們可以檢查輸入和實際驗證碼的文字... 如果妳希望它只是阿賈克斯的地方生成的驗證碼在Ajax調用鏈接.. – Froxz