当前位置:Gxlcms > php框架 > Ajax提交表单时验证码自动验证 php后端验证码检测

Ajax提交表单时验证码自动验证 php后端验证码检测

时间:2021-07-01 10:21:17 帮助过:15人阅读

本文通过源码展示如何实现表单提交前,验证码先检测正确性,不正确则不提交表单,更新验证码。

1、前端代码 index.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>验证码提交自验证</title>
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  6. <meta http-equiv="Content-Language" content="zh-CN" />
  7. </head>
  8. <body>
  9. <form action="doPost.php" method="POST">
  10. <div class="row">
  11. <label for="username">用户名</label>
  12. <input type="text" name="username" id="username" />
  13. </div>
  14. <div class="row">
  15. <label for="mod-captcha-code">验证码</label>
  16. <input name="code" id="mod-captcha-code" size="6" class="zjcaptcha" style="width:80px" type="text"/>
  17. <img class="code-img" style="height:30px;width:80px;" src="createcode.php?t=0" onclick="this.src=this.src.substring(0,this.src.indexOf('?')+1)+Math.random();return false;" />
  18. <script type="text/javascript" src="http://www.zjmainstay.cn/jquery/jquery-1.8.2.min.js"></script>
  19. <div class="yzmtips" style="color:red"></div>
  20. </div>
  21. <div class="row">
  22. <input type="submit" value="提交" class="submitBtn"/>
  23. </div>
  24. </form>
  25. <script>
  26. (function($){
  27. $(document).ready(function(){
  28. $(".submitBtn").click(function() {
  29. var obj = $(this);
  30. $.ajax({
  31. url:'checkcode.php',
  32. type:'POST',
  33. data:{code:$.trim($("input[name=code]").val())},
  34. dataType:'json',
  35. async:false,
  36. success:function(result) {
  37. if(result.status == 1) {
  38. obj.parents('form').submit(); //验证码正确提交表单
  39. }else{
  40. $(".code-img").click();
  41. $(".yzmtips").html('验证码错误!');
  42. setTimeout(function(){
  43. $(".yzmtips").empty();
  44. },3000);
  45. }
  46. },
  47. error:function(msg){
  48. $(".yzmtips").html('Error:'+msg.toSource());
  49. }
  50. })
  51. return false;
  52. })
  53. });
  54. })(jQuery);
  55. </script>
  56. </body>
  57. </html>

 2、后端验证码检测 checkcode.php

  1. <?php
  2. /**
  3. * 用户验证码验证文件
  4. * @Author:Zjmainstay
  5. * @version : 1.0
  6. * @creatdate: 2013-10-4
  7. */
  8. session_start();
  9. echo json_encode(array('status'=>(int)($_SESSION["CHECKCODE"] == $_POST['code'])));
  10. exit;

 源码下载地址:Ajax实现提交表单时验证码自动验证

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

人气教程排行