温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Ajax实现提交表单时验证码自动验证

发布时间:2021-08-20 21:23:57 来源:亿速云 阅读:114 作者:chen 栏目:开发技术

本篇内容介绍了“Ajax实现提交表单时验证码自动验证 ”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

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

1、前端代码 index.html

 <!DOCTYPE html>
<html>
<head>
 <title>验证码提交自验证</title>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <meta http-equiv="Content-Language" content="zh-CN" />
</head>
<body>
 <form action="doPost.php" method="POST">
  
  <div class="row">
   <label for="username">用户名</label>
   <input type="text" name="username" id="username" />
  </div>
  <div class="row">
   <label for="mod-captcha-code">验证码</label>
   <input name="code" id="mod-captcha-code" size="6" class="zjcaptcha"  type="text"/>
   <img class="code-img"  src="createcode.php?t=0" onclick="this.src=this.src.substring(0,this.src.indexOf('?')+1)+Math.random();return false;" />
   <script type="text/javascript" src="http://www.zjmainstay.cn/jquery/jquery-1.8.2.min.js"></script>
   <div class="yzmtips" ></div>
  </div>
  <div class="row">
   <input type="submit" value="提交" class="submitBtn"/>
  </div>
 </form>
<script>
(function($){
 $(document).ready(function(){
  $(".submitBtn").click(function() {
   var obj = $(this);
   $.ajax({
    url:'checkcode.php',
    type:'POST',
    data:{code:$.trim($("input[name=code]").val())},
    dataType:'json',
    async:false,
    success:function(result) {
     if(result.status == 1) {
      obj.parents('form').submit(); //验证码正确提交表单
     }else{
      $(".code-img").click();
      $(".yzmtips").html('验证码错误!');
      setTimeout(function(){
       $(".yzmtips").empty();
      },3000);
     }
    },
    error:function(msg){
     $(".yzmtips").html('Error:'+msg.toSource());
    }
   })
   return false;
  })
 });
})(jQuery);
</script>
</body>
</html>

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

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

“Ajax实现提交表单时验证码自动验证 ”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI