Home Web Front-end JS Tutorial How to implement verification code in ajax

How to implement verification code in ajax

Mar 30, 2018 pm 05:16 PM
ajax how verify

This time I will show you how to implement ajax verification code, and what are the precautions for ajax to implement verification code. The following is a practical case, let's take a look.

The example in this article shares the specific code for ajax to implement the verification code function for your reference. The specific content is as follows

First create a verification code:

<%@ page contentType="image/jpeg; charset=utf-8" 
  language="java" import="java.util.*,java.awt.*,java.awt.image.*,javax.imageio.*" 
  pageEncoding="UTF-8"%> 
<!-- 以上导入awt和awt.image包 --> 
<%! 
  //获取随机颜色 
  public Color getColor(){ 
   Random random = new Random(); 
   //使用rgb()随机产生颜色 
   int r = random.nextInt(256); 
   int g = random.nextInt(256); 
   int b = random.nextInt(256); 
    
   return new Color(r,g,b); 
  } 
   
  //获取随机数字 产生一个4位数 
  public String getNum(){ 
   String str = ""; 
   Random random = new Random(); 
   for(int i = 0;i < 4;i++){ 
    str += random.nextInt(10); //0-9 
   } 
   return str; 
  } 
%> 
 
<% 
  /* 清除缓存 */ 
  response.setHeader("pragma", "mo-cache"); 
  response.setHeader("cache-control", "no-cache"); 
  response.setDateHeader("expires", 0); 
  //产生矩形框 
  BufferedImage image = new BufferedImage(80,30,BufferedImage.TYPE_INT_RGB); 
  //获取画笔工具 
  Graphics g = image.getGraphics(); 
  //设置矩形框的颜色 
  g.setColor(new Color(200,200,200)); 
  //设置坐标和宽高 
  g.fillRect(0, 0, 80, 30); 
     
  //随机产生干扰线 
  for(int i = 0;i < 30;i++){ 
   Random random = new Random(); 
   int x = random.nextInt(80); 
   int y = random.nextInt(30); 
   int x1 = random.nextInt(x + 10); 
   int y1 = random.nextInt(y + 10); 
   //设置随机颜色 
   g.setColor(getColor()); 
   //画出来 
   g.drawLine(x, y, x1, y1); 
  } 
   
  //字的颜色和数字 
  g.setFont(new Font("Microsoft YaHei",Font.BOLD,16)); 
  g.setColor(Color.BLACK); 
  //获取随机数字 
  String checkNum = getNum(); 
   
  //给字拼接空格 
  StringBuffer sb = new StringBuffer(); 
  for(int i = 0;i < checkNum.length();i++){ 
   sb.append(checkNum.charAt(i) + " "); 
  } 
  //画出数字 
  g.drawString(sb.toString(), 15, 20); 
  //存入session域中 
  session.setAttribute("CHECKNUM", checkNum); //例如1010 
  //将图像以jpeg的形式通过字节流输出 
  ImageIO.write(image, "jpeg", response.getOutputStream()); 
  //清除缓存 
  out.clear(); 
  //放入body中 
  out = pageContext.pushBody(); 
%>
Copy after login
Put the verification code Compress it into an image, reference it in checkcode.jsp, and use ajax to send data to the server in this page

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 
<% 
String path = request.getContextPath(); 
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
%> 
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
 <head> 
 <base href="<%=basePath%>" rel="external nofollow" > 
  
 <title>验证码</title> 
  
 <meta http-equiv="pragma" content="no-cache"> 
 <meta http-equiv="cache-control" content="no-cache"> 
 <meta http-equiv="expires" content="0">  
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
 <meta http-equiv="description" content="This is my page"> 
 <style type="text/css"> 
  table{ 
   margin: 100px auto; 
  } 
   
 </style> 
 </head> 
 
 <body> 
  <table border="0" align="center"> 
   <tr> 
    <td>验证码</td> 
    <td><input type="text" name="checkcode" id="checkcodeID" maxlength="4" size="4"></td> 
    <td><img alt="加载失败" src="image.jsp"></td> 
    <td id="show">√√√</td> 
   </tr> 
  </table> 
 </body> 
 <script type="text/javascript"> 
  //去除空格 
  function trim(str){ 
   //从左侧开始替换空格 
   str = str.replace(/^\s*/,""); 
   //从左侧开始替换空格 
   str = str.replace(/\s$/,""); 
   return str; 
  } 
  
 </script> 
 
 <script type="text/javascript"> 
  //创建ajax对象 
  function createAjax(){ 
   var ajax = null; 
   try{ 
    ajax = new ActiveXObject("microsoft.xmlhttp"); 
   }catch(e){ 
    try{ 
     ajax = new XMLHttpRequest(); 
    }catch(e1){ 
     alert("请更换浏览器"); 
    } 
   } 
   return ajax; 
  } 
 </script> 
 
 
 <script type="text/javascript"> 
  document.getElementById("checkcodeID").onkeyup = function(){ 
   var checkcode = this.value; 
   //去除空格 
   checkcode = trim(checkcode); 
   if(checkcode.length == 4){ 
    //获取ajax对象 
    var ajax = createAjax(); 
    //获取去空格的内容 
     
    var method = "POST"; 
    var url = "${pageContext.request.contextPath}/CheckcodeServlet?time="+new Date().getTime(); 
    //准备发送异步请求 
    ajax.open(method, url); 
    //设置请求头POST提交方式才需要 
    ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded"); 
    //拼接实体内容 
    var content = "checkcode=" + checkcode;     
    //发送请求 
    ajax.send(content); 
     
    //监听服务器状态变化 
    ajax.onreadystatechange = function(){ 
     if(ajax.readyState == 4){ 
      if(ajax.status == 200){ 
       //获取服务器内容 
       var tip = ajax.responseText; 
       //获取图片路径 然后进行放入td中 
       var img = document.createElement("img"); 
       img.src = tip; 
       img.style.width = "14px"; 
       img.style.height = "14px"; 
       var td = document.getElementById("show"); 
       td.innerHTML = ""; 
       td.appendChild(img); 
      } 
     } 
    } 
     
   } 
    
  } 
 </script> 
</html>
Copy after login
Then write the server to receive the input information, determine whether it matches the verification code, and add the corresponding The path of the image is output in the form of an output stream

public class CheckcodeServlet extends HttpServlet { 
 @Override 
 protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
   throws ServletException, IOException { 
  req.setCharacterEncoding("utf-8"); 
  resp.setContentType("text/html;charset=utf-8"); 
  //图片路径 
  String tip = "images/MsgError.gif"; 
   
  String checkcode = req.getParameter("checkcode"); 
  //测试 
  System.out.println(checkcode); 
  //获取session域中的数字 
  String checkcodeService = (String) req.getSession().getAttribute("CHECKNUM"); 
  //判断 
  if (checkcode.equals(checkcodeService)) { 
   tip = "images/MsgSent.gif"; 
  } 
  //输出路径 
  PrintWriter pw = resp.getWriter(); 
  pw.write(tip); 
  pw.flush(); 
  pw.close(); 
 } 
}
Copy after login
When you enter the fourth number, a prompt will appear

Running result:

Believe it After reading the case in this article, you have mastered the method. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

Ajax+Servlet to implement non-refresh drop-down linkage (with code)

ajax to obtain json data How to use
for undefined

The above is the detailed content of How to implement verification code in ajax. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to verify signature in PDF How to verify signature in PDF Feb 18, 2024 pm 05:33 PM

We usually receive PDF files from the government or other agencies, some with digital signatures. After verifying the signature, we see the SignatureValid message and a green check mark. If the signature is not verified, the validity is unknown. Verifying signatures is important, let’s see how to do it in PDF. How to Verify Signatures in PDF Verifying signatures in PDF format makes it more trustworthy and the document more likely to be accepted. You can verify signatures in PDF documents in the following ways. Open the PDF in Adobe Reader Right-click the signature and select Show Signature Properties Click the Show Signer Certificate button Add the signature to the Trusted Certificates list from the Trust tab Click Verify Signature to complete the verification Let

Detailed method to unblock using WeChat friend-assisted verification Detailed method to unblock using WeChat friend-assisted verification Mar 25, 2024 pm 01:26 PM

1. After opening WeChat, click the search icon, enter WeChat team, and click the service below to enter. 2. After entering, click the self-service tool option in the lower left corner. 3. After clicking, in the options above, click the option of unblocking/appealing for auxiliary verification.

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

New features in PHP 8: Added verification and signing New features in PHP 8: Added verification and signing Mar 27, 2024 am 08:21 AM

PHP8 is the latest version of PHP, bringing more convenience and functionality to programmers. This version has a special focus on security and performance, and one of the noteworthy new features is the addition of verification and signing capabilities. In this article, we'll take a closer look at these new features and their uses. Verification and signing are very important security concepts in computer science. They are often used to ensure that the data transmitted is complete and authentic. Verification and signatures become even more important when dealing with online transactions and sensitive information because if someone is able to tamper with the data, it could potentially

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

See all articles