標籤:void tle 程式 this ram 3.1 port 測試 灰太狼
關於前端:
使用jquery-3.3.1.js記得要匯入奧---最後我會附加我的源碼的
哎我也不多說了新手加菜鳥jquery真的不太懂!看代碼吧!個別地方我會寫上我對本程式的理解。
關於後台也就是servlet
後台並沒有真正的連結資料庫你懂得加入你測試的話還要建表,很麻煩,大致寫了一個模板,以後你連結資料庫,改代碼的思路應該很簡單!!我說的有道理吧!!簡單的幾句話看代碼奧!!
index.jsp//by萌萌的灰太狼<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>在此處插入標題</title><script type="text/javascript" src="${pageContext.request.contextPath}/scripts/jquery-3.3.1.js"></script><script type="text/javascript">$(function () {//擷取要判斷的編輯框的id 之後就是一個被改變事件---$(":input[name=‘username‘]").change(function () {var val=$(this).val();val=$.trim(val);if(val!=""){var url="${pageContext.request.contextPath}/valiateUserName";//這個地址是你要判斷使用者是否存在的後台var args={"username":val,"time":new Date()};//這個參數是把編輯框裡的內容傳過去給後台了$.post(url,args,function(data){$("#message").html(data);}) //這句話的意思是返回的結果用html的格式寫到了標籤中顯示!!}})})</script></head><body><form action="" method="post">-------要判斷使用者是否存在的編輯框-------:<input type="text" name="username" size="60px" width="300px"><label id="message"></label><br></form></body></html>
servlet 檔案
package com.ajax;import java.io.IOException;import java.util.Arrays;import java.util.List;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Servlet implementation class valiateUserName */@WebServlet(asyncSupported = true, urlPatterns = { "/valiateUserName" })public class valiateUserName extends HttpServlet {/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub}/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);response.setCharacterEncoding("utf-8");request.setCharacterEncoding("utf-8");String username=request.getParameter("username");System.out.println("使用者名稱"+username);List<String> usernames =Arrays.asList("aaa","bbb","ccc");//相當於在這裡建立了一個數組,下面的話如果數組裡包括這幾個單詞那就前端提示資訊使用者已被註冊!String result=null;if(usernames.contains(username)){result="<font color=‘red‘>該使用者名稱已被使用</font>";System.out.println(result);}else {result="<font color=‘red‘>該使用者keyi使用</font>";System.out.println(result);}response.setContentType("text/html");//在這裡是傳回的文字格式設定為html格式response.getWriter().print(result);//將提示資訊傳回前端jsp頁面 }}
運行:
原始碼連結失效評論補連結::https://pan.baidu.com/s/1c3L06Ow
javaweb曆史上最簡單的使用Ajax判斷使用者名稱是否被註冊(不跳轉頁面奧!)