使用Servlet和Ajax完成登录注册的校验+Vue

一.Servlet登录注册校验

1.实现功能

实现功能:
	1.登录有记住密码选项
	2.使用Ajax输入用户名失去光标进行校验,不重复显示用户名可以使用,重复显示不可使用
	3.注册时加入验证码
	4.存入数据库中的密码经过MD5加密过

2.步骤

使用Servlet和Ajax完成登录注册的校验+Vue_第1张图片

(1) 与数据库建立连接

采用德鲁伊数据库连接池,导入数据库驱动jar包和德鲁伊相关jar包,添加依赖

使用Servlet和Ajax完成登录注册的校验+Vue_第2张图片

(2) 编写与数据库表相对应的实体类

User类:

package demo;

public class User {
     
    private int id;
    private String username;
    private String password;

    @Override
    public String toString() {
     
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }

    public int getId() {
     
        return id;
    }

    public void setId(int id) {
     
        this.id = id;
    }

    public String getUsername() {
     
        return username;
    }

    public void setUsername(String username) {
     
        this.username = username;
    }

    public String getPassword() {
     
        return password;
    }

    public void setPassword(String password) {
     
        this.password = password;
    }

    public User(int id, String username, String password) {
     
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public User() {
     
    }
}

(3) 编写登录界面

第一次进入界面时,进入登录界面,在登录界面的最下方写一个a标签以便跳转到注册界面

<%--
  Created by IntelliJ IDEA.
  User: user
  Date: 2020/8/19
  Time: 9:22
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>$Title$</title>


</head>
<body>
<div align="center">
  <h1>登录页面</h1>
  <form action="/20200819__1_war_exploded/denglu" method="post" id="myForm">
    用户名:<input type="text" name="username" id="uname"/><br>
    <span id="sp"></span>

    密码:<input type="password" name="password" id="pwd" placeholder="请输入密码"/><br>

      记住密码: <input type="checkbox" name="remeber"/>

      <br>
      <input type="submit" value="提交" />


  </form>

  <a href="index2.jsp">注册</a>


</div>
</body>
</html>

(4) 编写注册界面

在注册界面中查询数据库校验用户名是否重复

<%--
  Created by IntelliJ IDEA.
  User: user
  Date: 2020/8/19
  Time: 11:17
  To change this template use File | Settings | File Templates.
--%>

<%--注册页面--%>

<script src="js/jquery-3.5.1.js"></script>


<%--在注册里面使用Ajax判断用户名是否重复--%>


<%--

$.get("https://autumnfish.cn/api/joke/list", {
     
				"num": "1"
			}, function(resp) {
     
				alert(resp); //返回的就是个JSON对象
				alert(resp.msg);
			}, "json")
		})

--%>
<script>
    $(function () {
     
        // console.log($('#uname'));
        $('#uname').blur(function() {
     
            // alert($(this).val());
            var username= $(this).val();
            //发送Ajax请求
            $.get("/20200819__1_war_exploded/check?username="+username,function (data) {
     
                //  alert(data);

                if(data.flag=="yes"){
     
                    $('#sp').html("用户名可以使用")
                }else{
     
                    $('#sp').html("用户名已经存在")
                }

            },"json");

        })
    })
</script>


<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="utf-8" %>
<html>
<head>
    <title>Title</title>
    <script src="js/jquery-3.5.1.js"></script>
</head>
<body>
<div align="center">
    <form action="/20200819__1_war_exploded/login" method="get">
        用户名:
        <input type="text" name="username" id="uname" value="" placeholder="请输入用户名" maxlength="5" />
        <span id="sp"></span>
        <br>
        密码:
        <input type="password" name="password" placeholder="请输入密码" id="pwd"/>
        <br>



        <!-- 性别有多个 他们的name属性值要一样 -->
        性别:
        <input type="radio" name="sex" value="1" checked="checked" /><input type="radio" name="sex" value="0" /><input type="radio" name="sex" id="y" value="2" />
        <label for="y"></label>
        <br>
        爱好:
        <input type="checkbox" name="hobby" value="lanqiu" checked="checked" />
        篮球
        <input type="checkbox" name="hobby" value="zuqiu" checked="checked" />
        足球
        <input type="checkbox" name="hobby" id="pp" value="pingpang" />
        <label for="pp">乒乓球</label>
        <br>
        学历:
        <select name="xueli">
            <option value="babySchool">幼儿园</option>
            <option value="xiaoxue">小学</option>
            <option value="zhongxue">中学</option>
            <option value="daxue" selected="selected">大学</option>
        </select>
        <br>
        邮箱:
        <input type="email" name="user_email" />
        <br>
        你有你个女朋友:
        <input type="number" name="points" min="1" max="10" value="1" />
        <br>
        生日:
        <input type="date" name="birthday" />
        <br>
        个人描述:
        <textarea rows="10" cols="20" name="desc">

					</textarea>
        <br>

        <br>
        <img src="/20200819__1_war_exploded/code2" alt="" onclick="changeImg()" id="checkCode">
        <input type="text" name="checkCode"/>

        <br>
        <input type="submit" value="提交按钮" />

    <input type="reset" value="重置" />
        <br>
       <%-- <div style="color: red">
            <%=request.getAttribute("msg")==null?"": request.getAttribute("msg")%>
        </div>--%>
    </form>
</div>

</body>
</html>

<script type="text/javascript">
    function changeImg() {
     
        document.getElementById("checkCode").src="/20200819__1_war_exploded/code2?time="+new Date().getTime();
    }

</script>

(5) 封装登录和注册功能的类

package demo;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import utils.MD5Utils;

import javax.sql.DataSource;
import java.sql.Types;
import java.util.List;
import java.util.Properties;

public class UserLoginDenglu {
     
    private int i;

    //登录的方法
    public boolean dengLu(User user) throws Exception {
     
        String username = user.getUsername();
        String password = user.getPassword();
        Properties properties = new Properties();
        properties.load(this.getClass().getClassLoader().getResourceAsStream("druid.properties"));
        DataSource ds = DruidDataSourceFactory.createDataSource(properties);

        QueryRunner queryRunner = new QueryRunner(ds);
        User u = queryRunner.query("select username,password from user where username=? and password=?", new BeanHandler<User>(User.class), username, password);


        return u != null;
    }

    //注册的方法
    public boolean login(User user) throws Exception {
     
        int i=0;
        String username = user.getUsername();
        String password = user.getPassword();

        Properties properties = new Properties();
        properties.load(this.getClass().getClassLoader().getResourceAsStream("druid.properties"));
        DataSource ds = DruidDataSourceFactory.createDataSource(properties);
        QueryRunner queryRunner = new QueryRunner(ds);

        //查询数据库中的username
        User u = queryRunner.query("select username from user where username=?", new BeanHandler<User>(User.class), username);

        if (u==null) {
     
            MD5Utils md5Utils = new MD5Utils();
            String s = md5Utils.md5(password);
            i = queryRunner.update("insert into user values(?,?,?)", Types.NULL, username, s);
            //查询为空证明没这个user


        }else {
     
            System.out.println("注册失败");
        }

        return i>0;




    }
}

(6) 登录Servlet

package demo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "DengLuServlet", value = "/denglu")
public class DengLuServlet extends HttpServlet {
     
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     

        try {
     
            System.out.println("请求来了");
            //设置编解码格式
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");
            //根据文本框中的name属性获取值
            String username = request.getParameter("username");
            String password = request.getParameter("password");

            UserLoginDenglu ul = new UserLoginDenglu();
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);




            boolean flag = ul.dengLu(user);
            if (flag){
     
                String remeber = request.getParameter("remeber");
                if ("true".equals(remeber)){
     
                    System.out.println("密码记住了");
                    Cookie cookie = new Cookie("remeber",user.getUsername());

                    cookie.setMaxAge(60*60*24*7);
                    response.addCookie(cookie);
                }


                //登录成功跳转到主页面
                request.setAttribute("username",user.getUsername());
                request.getRequestDispatcher("/WEB-INF/home.jsp").forward(request,response);
            }else {
     
                request.setAttribute("msg","用户名或密码错误");
                request.getRequestDispatcher("/index.jsp").forward(request,response);
            }

        } catch (Exception e) {
     
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     
        this.doPost(request, response);
    }
}

(7) 注册Servlet

package demo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//注册
@WebServlet(name = "LoginServlet", value = "/login")
public class LoginServlet extends HttpServlet {
     
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     
        try {
     
            System.out.println("注册请求来了");
            //设置编解码格式
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");



                //根据文本框中的name属性获取值
                String username = request.getParameter("username");
                String password = request.getParameter("password");

                //获取用户提交的验证码
                UserLoginDenglu ul = new UserLoginDenglu();
                User user = new User();
                user.setUsername(username);
                user.setPassword(password);

                boolean b = ul.login(user);


                if (b){
     
                    //注册成功
                    //注册成功跳转到主页面
                    request.setAttribute("username",user.getUsername());
                   request.getRequestDispatcher("/WEB-INF/home.jsp").forward(request,response);


                }else {
     
                    //request.setAttribute("msg","用户名已存在或格式错误");

                    request.getRequestDispatcher("/index2.jsp").forward(request,response);

                }





        } catch (Exception e) {
     
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     
        this.doPost(request, response);
    }
}

(8) 验证码工具类

Servlet

package demo;

import utils.VerifyCode;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

@WebServlet(name = "ServletCode", value = "/code2")
public class ServletCode extends HttpServlet {
     
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     
        //验证码
        int width = 200;
        int height = 100;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        //生成对应宽高的初始图片
       // String randomText = VerifyCode.drawRandomText(width, height, verifyImg);

        //生成对应宽高的初始图片
        String randomText = VerifyCode.drawRandomText(width, height, image);
        //单独的一个类方法,出于代码复用考虑,进行了封装。
        //功能是生成验证码字符并加上噪点,干扰线,返回值为验证码字符
        request.getSession().setAttribute("verifyCode", randomText);
        response.setContentType("image/png");//必须设置响应内容类型为图片,否则前台不识别
        OutputStream os = response.getOutputStream(); //获取文件输出流
        ImageIO.write(image, "png", os);//输出图片流
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     
        this.doPost(request, response);
    }
}

class

package demo;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class VerifyCode {
     
    // https://blog.csdn.net/piaoyinluo2316/article/details/83754145
    public static String drawRandomText(int width, int height, BufferedImage verifyImg) {
     

        Graphics2D graphics = (Graphics2D) verifyImg.getGraphics();

        graphics.setColor(Color.WHITE);//设置画笔颜色-验证码背景色

        graphics.fillRect(0, 0, width, height);//填充背景

        graphics.setFont(new Font("微软雅黑", Font.BOLD, 40));

        //数字和字母的组合

        String baseNumLetter = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";

        StringBuffer sBuffer = new StringBuffer();

        int x = 10;  //旋转原点的 x 坐标

        String ch = "";

        Random random = new Random();

        for (int i = 0; i < 4; i++) {
     

            graphics.setColor(getRandomColor());

            //设置字体旋转角度

            int degree = random.nextInt() % 30;  //角度小于30度

            int dot = random.nextInt(baseNumLetter.length());

            ch = baseNumLetter.charAt(dot) + "";

            sBuffer.append(ch);

            //正向旋转

            graphics.rotate(degree * Math.PI / 180, x, 45);

            graphics.drawString(ch, x, 45);

            //反向旋转

            graphics.rotate(-degree * Math.PI / 180, x, 45);

            x += 48;

        }

        //画干扰线

        for (int i = 0; i < 6; i++) {
     

            // 设置随机颜色

            graphics.setColor(getRandomColor());

            // 随机画线

            graphics.drawLine(random.nextInt(width), random.nextInt(height),

                    random.nextInt(width), random.nextInt(height));

        }

        //添加噪点

        for (int i = 0; i < 30; i++) {
     

            int x1 = random.nextInt(width);

            int y1 = random.nextInt(height);

            graphics.setColor(getRandomColor());

            graphics.fillRect(x1, y1, 2, 2);

        }
        return sBuffer.toString();
    }

    /**
     * 随机取色
     */

    private static Color getRandomColor() {
     
        Random ran = new Random();
        Color color = new Color(ran.nextInt(256),
                ran.nextInt(256), ran.nextInt(256));
        return color;
    }
}

(9)MD5加密

package utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Utils {
     
    public static String md5(String str) throws NoSuchAlgorithmException {
     
        //MD5 属于单向加密,加密完是32位
        MessageDigest instance = MessageDigest.getInstance("MD5");
        byte[] digest = instance.digest(str.getBytes());
        StringBuilder sb = new StringBuilder();
        for (byte by : digest) {
     
            int n=by&0xff;
            String s = Integer.toHexString(n);

            if(s.length()<2){
     
                s=s+"0";
            }
            //System.out.println(s);
            sb.append(s);
        }
        String md5Str = sb.toString();
        //System.out.println(md5Str);
        //System.out.println(md5Str.length());
        return md5Str;
    }
}

3.成果展示

主界面:
使用Servlet和Ajax完成登录注册的校验+Vue_第3张图片
注册界面:
使用Servlet和Ajax完成登录注册的校验+Vue_第4张图片
注册成功跳转到用户个人界面:
使用Servlet和Ajax完成登录注册的校验+Vue_第5张图片
注册失败提示用户名已存在:
使用Servlet和Ajax完成登录注册的校验+Vue_第6张图片
注册符合要求提示用户名可以使用:
使用Servlet和Ajax完成登录注册的校验+Vue_第7张图片

登录失败继续跳转到登录界面:
使用Servlet和Ajax完成登录注册的校验+Vue_第8张图片
登录成功跳转到用户个人信息界面:
使用Servlet和Ajax完成登录注册的校验+Vue_第9张图片
存入数据库中的密码用md5加密:
在这里插入图片描述

二.案例

1.表单验证

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			input[name]{
     
				width: 200px;
				height: 25px;
			}
			input[type="radio"]{
     
				width: 50px;
				height: 15px;
			}
			input[type="checkbox"]{
     
				width: 50px;
				height: 15px;
			}
			input[type="text-area"]{
     
				width: 200px;
				height: 200px;
			}
		</style>
	</head>
	<body>
		   <div id="" align="center">
			<h2>用户注册</h1>
			<form action="#" method="get" onsubmit="return checkForm()">
				用户名<input type="text" name="username" id="uname" value="" placeholder="请输入用户名6-16位字母" onblur="checkUserName()"/>
				<p id="name"></p>
				<br>
				密码<input type="password" name="password" id="code" value="" placeholder="请输入用户名6-16位数字0不能开头" onblur="checkPassword()"/>
				<p id="pass"></p>
				<br>
				确认密码<input type="password" name="confirm" id="confirm" value="" placeholder="请确认你的密码" onblur="confirmPassWord()" />
				<p id="c"></p>
				性别: <input type="radio" name="sex" id="man" value="" /><label for="man"></label>
				      <input type="radio" name="sex" id="woman" value="" /><label for="woman"></label>
					  <p id="sex"></p>
					  <br>
			    爱好: <input type="checkbox" name="ah" id="pb" value="" />跑步
					  <input type="checkbox" name="ah" id="cg" value="" />唱歌
					  <input type="checkbox" name="ah" id="ds" value="" />读书
					  <p id="ah"></p>
					  <br>
				个人描述:<input type="text-area" name="gr" id="gr" value="" onblur="checkText()" /><span id="text"></span>
				<br>
				<input type="submit" value="注册" onclick="checkSelect()"/>
			</form>
		 </div>
	</body>
	<script type="text/javascript">
		function checkForm(){
     
			return checkUserName()&&checkPassword()&&confirmPassWord()&&checkSelect()&&checkText();
		}
		function checkUserName(){
     
			var username=document.getElementById("uname").value.trim();
			var regx=/^[a-zA-Z]{
     6,16}$/;
			var flag=regx.test(username);
			var p1=document.getElementById("name");
		    if(flag){
     
				
				p1.innerHTML = "用户名输入正确✔"
				document.getElementById("uname").style.border="2px lightgreen solid"
			}else{
     
				p1.innerText="用户名输入错误✘";
				p1.style.color="red";
				document.getElementById("uname").style.border="1px red solid"
			}
			return flag;
		}
		function checkPassword(){
     
			var password=document.getElementById("code").value.trim();
			var regx=/^[1-9][0-9]{
     5,15}$/;
			var flag=regx.test(password);
			var p2=document.getElementById("pass");
			if(flag){
     
				p2.innerHTML = "密码输入正确✔"
				document.getElementById("code").style.border="1px lightgreen solid"
			}else{
     
				p2.innerText="密码输入错误✘";
				p2.style.color="red";
				document.getElementById("code").style.border="1px red solid"
			}
			return flag;
		}
		function confirmPassWord(){
     
			var code=document.getElementById("confirm").value.trim();
			var pcode=document.getElementById("code").value;
			if(code==pcode){
     
				document.getElementById("confirm").style.border="1px green solid";
				var p3=document.getElementById("c");
				p3.innerText="密码确认完成✔";
				p3.style.color="lightgreen";
				return true;
			}else{
     
				document.getElementById("confirm").style.border="1px red solid";
				var p3=document.getElementById("c");
				p3.innerText="密码输入不一致✘";
				p3.style.color="red";
				return false;
			}
		}
		function checkSelect(){
     //问题
			
			var testSex=false;
			var testAh=false;
			var radio=document.getElementsByName("sex");
			var checkbox=document.getElementsByName("ah");
			for(var i=0;i<radio.length;i++){
     
				if(radio[i].checked==true){
     
					testSex=true;
					break;
				}
			}
			if(testSex==false){
     
				var pp=document.getElementById("sex");
				pp.innerText="未勾选性别✘";
				pp.style.color="red";
			}else{
     
				var pp=document.getElementById("sex");
				pp.innerText="";
			}
		    for(var i=0;i<checkbox.length;i++){
     
				if(checkbox[i].checked==true){
     
					testAh=true;
					break;
				}
			}
			if(testAh==false){
     
				var pp=document.getElementById("ah");
				pp.innerText="未勾选爱好✘";
				pp.style.color="red";
			}else{
     
				var pp=document.getElementById("ah");
				pp.innerText="";
			}
			if(testAh&&testSex){
     
				return true;
			}else{
     
				return false;
			}
			
		}
	     function checkText(){
     
	     	var area=document.getElementById("gr").value;
	     	if(area.length<50){
     
	     		var t=document.getElementById("text");
	     		t.innerText="字数不得少于50字✘";
	     		t.style.color="red";
	     		return false;
	     	}else{
     
				var t=document.getElementById("text");
				t.innerText="";
	     		return true;
	     	}
	     	
	     }
	</script>
</html>

2.轮播图


```<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			#wai{
     
				width: 230px;
				height: 320px;
				border: 1px black solid;
				overflow: hidden;
			}
			#nei{
     
				width: 920px;
				height: 320px;
				transition: margin-left 1s;
			}
			#p1{
     
				width: 230px;
				height: 320px;
				background-image: url(img/main02_centent_01.png);
				float: left;
			}
			#p2{
     
				width: 230px;
				height: 320px;
				background-image: url(img/main02_centent_02.png);
				float: left;
			}
			#p3{
     
				width: 230px;
				height: 320px;
				background-image: url(img/main02_centent_03.png);
				float: left;
			}
			#p4{
     
				width: 230px;
				height: 320px;
				background-image: url(img/main02_centent_04.png);
				float: left;
			}
			#dot{
     
				width:230px;
				position: absolute;
				margin-left: auto;
				margin-top: 300px;
				/*border: 1px black solid;*/
				display: flex;
				justify-content: center;
			}
			.dot{
     
				width: 14px;
				height: 14px;
				border: 1px #000000 solid;
				border-radius: 7px;
				font-size: 10px;
				margin-left: 10px;
			    text-align: center;
				background: grey;
			}
			.dot:hover{
     
				cursor: pointer;
			}
		</style>
	</head>
	<body>
		<div id="wai" onmouseover="stopRoll()" onmouseout="startRoll()">
			<div id="dot">
				<div id="d1" class="dot" onclick="jumpPicture()">
					1
				</div>
				<div id="d2" class="dot" onclick="jumpPicture()">
					2
				</div>
				<div id="d3" class="dot" onclick="jumpPicture()">
					3
				</div>
				<div id="d4" class="dot" onclick="jumpPicture()">
					4
				</div>
			</div>
			<div id="nei">
				<div id="p1">
					
				</div>
				<div id="p2">
					
				</div>
				<div id="p3">
					
				</div>
				<div id="p4">
					
				</div>
			</div>
			
		</div>
	</body>
	<script type="text/javascript">
		var content=document.getElementById("nei");
		var count=0;
		var timer;
		var dots=document.getElementsByClassName("dot")
		//将第一个点设置为红色
		dots[0].style.background="red";
		function roll(){
     
			//每次执行先清空颜色
			clearColor();
			count++
			if (count>3){
     
				count = 0;
			}
			dots[count].style.background="red";
			content.style.marginLeft = (-1 * 230 * count) + "px";
		}
		timer=window.setInterval('roll()',2000);
		//鼠标移动到层,暂停播放
		function stopRoll(){
     
			window.clearInterval(timer);
		}
		//鼠表离开,继续播放
		function startRoll(){
     
			timer=window.setInterval('roll()',2000);
		}
		//清空颜色的函数
		function clearColor(){
     
			for(var i=0;i<dots.length;i++){
     
				dots[i].style.background="gray";
			}
		}
		//作业:点击对应的序号,跳转到对应的图片
		function jumpPicture(){
     
			var index;
			var dot=event.target;
			for(var i=0;i<dots.length;i++){
     
				if(dot==dots[i]){
     
					index=i;
				}
			}
			clearColor();
			dots[index].style.background="red";
			content.style.marginLeft = (-1 * 230 * index) + "px";
			//跳转后,继续播放下一张图片
		    count=index;
		}
	</script>
</html>

3.三级联动


<html>
	<head>
		<meta charset="utf-8">
		<title>title>
	head>
	<body>
		<select name="s" id="shenfen" onchange="selectProvince()">
			<option value="x">---请选择省份---option>
		select>
		<select name="c" id="city" onchange="selectCity()">
			<option value="xx">---请选择城市---option>
		select>
		<select name="district" id="district">
			<option value="xxx">---请选择行政区---option>
		select>
	body>
	<script type="text/javascript">
		var provinceArr=['陕西','河南'];
		var cityArr=[['西安','宝鸡','汉中','商洛','延安'],['郑州','开封','洛阳']];
		var districtArr=[
		       [
		['雁塔区','碑林区','高新区','莲湖区'],
		['金台区','渭滨区','陈仓区'],
		['汉台区','南郑区'],
		['洛南县','丹凤县','商南县','山阳县'],
		['宝塔区','延长县','延川县','子长县']
		                       ],
				[
				  ['中原区','二七区','金水区','惠济区'],
				  ['龙亭区','鼓楼区','禹王台区','顺河区'],
				  ['涧西区','西工区','老城区','瀍河区']
				]			   
		];

		var sf=document.getElementById("shenfen");
		var citys=document.getElementById("city");
		var districts=document.getElementById("district");
		//创建省份的下拉列表
		for(var i=0;i<provinceArr.length;i++){
      
			var p=document.createElement("option");
			var pName=document.createTextNode(provinceArr[i]);
			p.appendChild(pName);
			sf.appendChild(p);
		}
		function selectProvince(){
      
			//先清空城市和区的下拉列表
			citys.length=1
	        districts.length=1;
			var index=sf.selectedIndex-1;
			var c=cityArr[index];
			for(let i=0;i<c.length;i++){
      
				var op=document.createElement("option");
				var cityName=document.createTextNode(c[i]);
				op.appendChild(cityName);
				citys.appendChild(op);
			}
		}
		function selectCity(){
      
			//先清空区的下拉列表
			districts.length=1;
			var provinceIndex;
			var p=sf.getElementsByTagName("option");
			for(var i=1;i<p.length;i++){
      
				if(p[i].selected==true){
      
					provinceIndex=i;
					break;
				}
			};
			var cityIndex;
			var c=citys.getElementsByTagName("option");
			for(var i=1;i<c.length;i++){
      
				if(c[i].selected==true){
      
					cityIndex=i;
					break;
				}
			};
		    var d=districtArr[provinceIndex-1][cityIndex-1];
			for(let i=0;i<d.length;i++){
      
				var op=document.createElement("option");
				var districtName=document.createTextNode(d[i]);
				op.appendChild(districtName);
				districts.appendChild(op);
			}
		}
	script>
html>

4.天气预报


<html lang="en">

	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<meta http-equiv="X-UA-Compatible" content="ie=edge" />
		<title>天知道title>
		<link rel="stylesheet" href="css/reset.css" />
		<link rel="stylesheet" href="css/index.css" />
	head>

	<body>
		<div class="wrap" id="app">
			<div class="search_form">
				<div class="logo"><img src="img/logo.png" alt="logo" />div>
				<div class="form_group">
					<input type="text" id="city" class="input_txt" placeholder="请输入查询的天气" />
					<button class="input_sub" onclick="sendAjax()">
						搜 索
					button>
				div>
				<div class="hotkey">
					<a href="javascript:;">北京a>
					<a href="javascript:;">上海a>
					<a href="javascript:;">广州a>
					<a href="javascript:;">深圳a>
				div>
			div>
			<ul class="weather_list" id="myUL">
				
				<li>
					<div class="info_type"><span class="iconfont">小雨span>div>
					<div class="info_temp">
						<b>低温 20℃b>
						~
						<b>高温 23℃b>
					div>
					<div class="info_date"><span>25日星期六span>div>
				li>
			ul>
		div>

	body>

html>
<script type="text/javascript">
	function sendAjax() {
      
		var cityName = document.getElementById("city").value.trim();
		if (!cityName) {
      
			alert("请输入一个城市")
			return
		}
		//alert(cityName);
		var xmlhttp;
		xmlhttp = new XMLHttpRequest();
		//2.向服务器发送请求
		//如需将请求发送到服务器,我们使用 XMLHttpRequest 对象的 open() 和 send() 方法:
		//3.发送请求
		/* 
		method:请求的类型;GET 或 POST 
		url:文件在服务器上的位置 ,后台接口地址
		async:true(异步)或 false(同步) */

		xmlhttp.open("GET", "http://wthrcdn.etouch.cn/weather_mini?city=" + cityName, true);
		xmlhttp.send();
		xmlhttp.onreadystatechange = function() {
      
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      
				//4.如需获得来自服务器的响应,请使用 XMLHttpRequest 对象的 responseText;
				var jsonStr = xmlhttp.responseText;
				//console.log(jsonStr);
				//把JSON字符串,解析成JSON对象
				var obj = JSON.parse(jsonStr);
				var arr = obj.data.forecast;
				var jsonYesterday=obj.data.yesterday;//获取昨天的json对象,作为参数传入;
				//console.log(arr);
				showData(arr,jsonYesterday);
			}
		}
	}

	function showData(arr,jsonYesterday) {
      
		//console.log(arr);
		var myUL=document.getElementById("myUL");
		
		var liStr="";
		//先拼接昨天的天气
		liStr+=`
  • ${ jsonYesterday.type}
    ${ jsonYesterday.low} ~ ${ jsonYesterday.high}
    ${ jsonYesterday.date}
  • `
    ; for (var i = 0; i < arr.length; i++) { var json = arr[i]; //console.log(json); liStr+=`
  • ${ json.type}
    ${ json.low} ~ ${ json.high}
    ${ json.date}
  • `
    ; } myUL.innerHTML=liStr; }
    script>

    三.Vue作业

    1.手机归属地查询

    
    <html>
    	<head>
    		<meta charset="utf-8">
    		<title>title>
    		<script src="js/jquery.js" type="text/javascript" charset="utf-8">script>
    		<style type="text/css">
    			body{
          
    				border: 0px #808080 solid;
    				margin-left: 10%;
    				margin-right: 10%;
    				height: 1000px;
                    text-align:center ;
    				flex-wrap:nowrap;
    			}
    	         h1{
          
    				 margin-left: 50px;
    				 min-width: 500px;
    			 }
    			input{
          
    				min-width: 600px;
    				height: 30px;
    				border: 1px gray solid;
    				align:center;
    				margin-left: 100px;
    			}
    			button{
          
    				min-width: 100px;
    				height: 34px;
    				border: 1px gray solid;
    				margin-left: -5px;
    			}
    			table{
          
    				margin-top: 20px;
    				margin-left: 400px;
    				border: 1px aqua solid;
    			}
    		style>
    	head>
    	<body>
    	
    			<h1 align="center">手机号码归属地在线查询h1>
    			<input type="text" id="sj" value="" placeholder="请输入手机号码" />
    			<button type="button" >查询button>
    			<table border="1" cellspacing="0" cellpadding="" id="t">
    				
    			table>
    	body>
    	<script type="text/javascript">
    		$('button').click(function(){
          
    			var telNum =$("input").val();
    			$.ajax({
          
    			   type:"GET",
    			   url:"https://tcc.taobao.com/cc/json/mobile_tel_segment.htm",
    			   jsonp:"callback",
    			   data:{
          
    				 tel: telNum 
    			   },
    			   success:function(resData){
          
    				   showData(resData)
    			   },
    			   dataType:"jsonp"
    			})
    		});
    		
    		function showData(resData){
          	
    	     
    		 $("#t").width('500px');
    		 $("#t").height('500px');
    		 $('#t').css('cellspacing','0px');
    		 var trStr="";
    		 trStr+=`
    		 
    		       查询
    		 `;
    		             
    		 			 trStr+=`
    		 			       您查询的手机号码段
    		 			 	   ${
            resData.telString}
    		 			 `;
    		 			 trStr+=`
    		 			       卡号归属地
    		 			 	   ${
            resData.province}
    		 			 `;
    		 			 trStr+=`
    		 			       卡类型
    		 			 	   ${
            resData.catName}
    		 			 `;
    		 			 trStr+=`
    		 			       区号
    		 			 	   ${
            resData.areaVid}
    		 			 `;
    		 $("#t").html(trStr);
    		}
    	script>
    html>
    
    

    2.图片切换

    
    <html>
    	<head>
    		<meta charset="utf-8">
    		<title>title>
    		<script src="js/vue.js" type="text/javascript" charset="utf-8">script>
    		<style type="text/css">
    			.p1Class{
          
    				background: url(images/bingtu.png);
    				width: 300px;
    				height: 300px;
    			}
    			.p2Class{
          
    				background: url(images/dianbg.png);
    				width: 300px;
    				height: 300px;
    			}
    			.p3Class{
          
    				background: url(images/gongsi1.png);
    				background-size: 100%;
    				width: 300px;
    				height: 300px;
    			}
    		style>
    	head>
    	<body>
    		<div id="app">
    			<button type="button" @click="switchPicture1()" >按钮1button>
    			<button type="button" @click="switchPicture2()" >按钮2button>
    			<button type="button" @click="switchPicture3()" >按钮3button>
    			<div id="p1" :class="a">
    				
    			div>
    		div>
    	body>
    	<script type="text/javascript">
    		new Vue({
          
    			el:"#app",
    			data:{
          
    				'a':"p1Class",
    			},
    			methods:{
          
    				switchPicture1(){
          
    				   this.a="p1Class"
    				},
    				switchPicture2(){
          
    					this.a="p2Class"
    				},
    				switchPicture3(){
          
    					this.a="p3Class"
    				}
    			}
    		})
    	script>
    html>
    
    

    3.vue的天气预报

    
    <html lang="en">
    
    	<head>
    		<meta charset="UTF-8" />
    		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
    		<meta http-equiv="X-UA-Compatible" content="ie=edge" />
    		<title>天知道title>
    		<link rel="stylesheet" href="css/reset.css" />
    		<link rel="stylesheet" href="css/index.css" />
    		<script src="js/vue.js" type="text/javascript" charset="utf-8">script>
    		<script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js">script>
    	head>
    
    	<body>
    		<div class="wrap" id="app">
    			<div class="search_form">
    				<div class="logo"><img src="img/logo.png" alt="logo" />div>
    				<div class="form_group">
    					<input type="text" id="city" class="input_txt" placeholder="请输入查询的天气" v-model="cityName"/>
    					<button class="input_sub" @click="send()">
    						搜 索
    					button>
    				div>
    				<div class="hotkey">
    					<a href="javascript:;">北京a>
    					<a href="javascript:;">上海a>
    					<a href="javascript:;">广州a>
    					<a href="javascript:;">深圳a>
    				div>
    			div>
    		    <ul class="weather_list" id="myUL" >
    			
    				<li v-for="(ele,index) in jsonArr" :key="index" >
    					<div class="info_type"><span class="iconfont">{
        {ele.type}}span>div>
    					<div class="info_temp">
    						<b>{
        {ele.low}}b>
    						~
    						<b>{
        {ele.high}}b>
    					div>
    					<div class="info_date"><span>{
        {ele.date}}span>div>
    				li>
    			ul>
    		div>
    
    	body>
    
    html>
    <script type="text/javascript">
         new Vue({
          
    		 el:"#app",
    		 data:{
          
    			 cityName:'',
    			 jsonArr:[]
    		 },
    		 methods:{
          
    			 send(){
          
    				 this.$http.get("http://wthrcdn.etouch.cn/weather_mini",{
          
    					 params:{
          
    						 city:this.cityName
    					 }
    				 }).then(function(res){
          
    					 var arr=res.body.data.forecast;
    					for(var i=0;i<arr.length;i++){
          
    						this.jsonArr.push(arr[i]);
    					};
    					//console.log(this.jsonArr);
    					
    				 },function(res){
          
    					 alert("请求失败");
    				 })
    			 }
    			
    		 }
    	 });
    	
    	
    script>
    
    
    

    4.学生信息以表格展示

    
    <html>
    	<head>
    		<meta charset="utf-8">
    		<title>title>
    		<script src="js/vue.js" type="text/javascript" charset="utf-8">script>
    	head>
    	<body>
    		<div id="app">
    			<h1 align="center">添加学生h1>
    			<center>
    			<input type="text" id="" value="" placeholder="请输入你的姓名" v-model="name"/>
    			<input type="text" id="" value="" placeholder="请输入你的年龄" v-model="age"/>
    			<button type="button" @click="add()">添加button>
    			<br>
    			<input type="text" id="" value="" placeholder="请输入修改的姓名" v-model="newName"/>
    			<input type="text" id="" value="" placeholder="请输入修改的年龄" v-model="newAge"/>
    			center>
    			<br><br><br>
    			<h3 align="center">学生信息表h3>
    			<table border="1px" cellspacing="0" cellpadding="" width="50%" align="center">
    				<tr height="50px"><th>序号th><th>姓名th><th>年龄th><th>操作th>tr>
    				<tr align="center" v-for="(ele,index) in jsonArr" :key="index">
    					<td>{
        {index+1}}td>
    					<td>{
        {ele.name}}<a href="#" @click="changeName(ele,index)">修改a>td>
    					<td>{
        {ele.age}}<a href="#" @click="changeAge(ele,index)">修改a>td>
    					<td><a href="#" @click="del(index)">删除a>td>
    				tr>
    				<tr><td colspan="4" align="center">
    				<a href="#" @click="delAll()" v-if="checkData()">全部删除a>
    				<a href="#" v-else>没有数据,请你添加a>
    				td>tr>
    			table>
    		div>
    	body>
    	<script type="text/javascript">
    		new Vue({
          
    			el:"#app",
    			data:{
          
    				name:'',
    				age:'',
    				jsonArr:[],
    				newName:'',
    				newAge:'',
    			},
    			methods:{
          
    				add(){
          
    					if(!this.name||!this.age){
          
    						alert("姓名或年龄不能为空");
    						return;
    					}
    					var student={
          "name":this.name,"age":this.age};
    					this.jsonArr.push(student);
    				},
    				delAll(){
          
    					if(confirm("确认全部删除吗?")){
          
    						this.jsonArr=[];
    					}
    					
    				},
    				del(index){
          
    					this.jsonArr.splice(index,1);
    				},
    				changeName(e,index){
          
    					if(confirm("确认修改姓名吗?")){
          
    						var newStudent={
          "name":this.newName,"age":e.age};
    						this.jsonArr.splice(index,1,newStudent);
    						this.newName='';
    					}else{
          
    						return;
    					}
    				},
    				changeAge(e,index){
          
    					if(confirm("确认修改年龄吗?")){
          
    						var newStudent={
          "name":e.name,"age":this.newAge};
    						this.jsonArr.splice(index,1,newStudent);
    						this.newAge='';
    					}else{
          
    						return;
    					}
    				},
    				checkData(){
          
    					if(this.jsonArr.length!=0){
          
    						return true;
    					}else{
          
    						return false;
    					}
    				}
    			}
    		})
    	script>
    html>
    
    

    5.过滤搜索

    
    <html>
    	<head>
    		<meta charset="utf-8">
    		<title>title>
    		<script src="js/vue.js" type="text/javascript" charset="utf-8">script>
    	head>
    	<body>
    		<div id="app">
    			<center>
    				<input type="text" id="" value="" placeholder="请输入搜索的内容 按enter搜索" v-model="content" />
    				<ul>
    					<li v-for="(ele,index) in newJsonArr" :key="index">
    					{
        {index}}---{
        {ele.name}}---{
        {ele.age}}---{
        {ele.sex}}
    					li>
    				ul>
    				<button type="button" @click="sortArr(1)">升序排列button>
    				<button type="button" @click="sortArr(2)">降序排列button>
    				<button type="button" @click="sortArr(3)">默认排序button>
    			center>
    		div>
    	body>
    	<script type="text/javascript">
    		new Vue({
          
    			el:"#app",
    			data:{
          
    				content:'',
    				jsonArr:[
    					{
              
    						'id':1,
    						'name': 'zhangsan',
    						'age': 25,
    						'sex': '男'
    					}, {
          
    						'id':2,
    						'name': 'lisi',
    						'age': 23,
    						'sex': '男'
    					}, {
          
    						'id':3,
    						'name': 'wangwu',
    						'age': 24,
    						'sex': '男'
    					}, {
          
    						'id':4,
    						'name': 'zhaoliu',
    						'age': 26,
    						'sex': '男'
    					}
    				],
    			},
    			computed:{
          
    				newJsonArr: function(){
          
    					var text=this.content;
    					var arr=this.jsonArr.filter(function(ele){
          
    						if(ele.name.indexOf(text)!=-1){
          
    							return true;
    						}
    					});
    					return arr;
    				}
    			},
    			methods:{
          
    				sortArr(num){
          
    					if(num==1){
          
    						this.jsonArr.sort(function(a,b){
          
    							return a.age-b.age;
    						});
    					}else if(num==2){
          
    						this.jsonArr.sort(function(a,b){
          
    							return b.age-a.age;
    						});
    					}else if(num==3){
          
    						this.jsonArr.sort(function(a,b){
          
    							return a.id-b.id;
    						});
    						
    					}
    				}
    			}
    		})
    	script>
    html>
    
    

    你可能感兴趣的:(Vue,bbs,tiff,ssis,ugui,dalvik)