JavaWeb—Ajax

系列文章目录

JavaWeb中Ajax的使用
本章内容所需资源
链接:https://pan.baidu.com/s/1a7pixcZmuPbZJPsAMH_qJg?pwd=1111
提取码:1111


文章目录

  • 系列文章目录
  • 前言
  • 一、AJAX快速入门
  • 二、案例
  • 三、Axios异步框架
  • 四、JSON
    • 1.JSON基础语法
    • 2.JSON数据和Java对象相互转换
    • 3.案例
      • 1.查询所有品牌代码
      • 2.添加品牌代码
  • 总结


前言

JavaWeb—Ajax_第1张图片

JavaWeb—Ajax_第2张图片


一、AJAX快速入门

JavaWeb—Ajax_第3张图片

package org.example.web.servlet;

import javax.servlet.annotation.WebServlet;
import java.io.IOException;

@WebServlet("/ajaxServlet")
public class AjaxServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

        response.getWriter().write("Hello Ajax ");
    }
}

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>


body>
<script>
    // 1.创建核心对象
    var xhttp;
    if (window.XMLHttpRequest) {
        xhttp = new XMLHttpRequest();
    } else {
        xhttp = new ActiveXObject("Microsoft.XMLHTTP")
    }
    // 2.发送请求
    xhttp.open("Get", "http://localhost:8080/ajax-demo/ajaxServlet")
    xhttp.send();
    // 3.获取响应
    xhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            alert(this.responseText);
        }
    }
script>
html>

二、案例

JavaWeb—Ajax_第4张图片

package org.example.web.servlet;

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("/selectUserServlet")
public class SelectUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1.接收用户名
        String username = request.getParameter("username");
        //2.调用service方法查询User对象
        boolean flag=true;
        //3.响应标记
        response.getWriter().write(""+flag);
    }
}

页面代码(CSS等静态资源参考)

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>欢迎注册title>
    <link href="css/register.css" rel="stylesheet">
head>
<body>

<div class="form-div">
    <div class="reg-content">
        <h1>欢迎注册h1>
        <span>已有帐号?span> <a href="login.html">登录a>
    div>
    <form id="reg-form" action="#" method="get">

        <table>

            <tr>
                <td>用户名td>
                <td class="inputs">
                    <input name="username" type="text" id="username">
                    <br>
                    <span id="username_err" class="err_msg" style="display: none">用户名已存在span>
                td>

            tr>

            <tr>
                <td>密码td>
                <td class="inputs">
                    <input name="password" type="password" id="password">
                    <br>
                    <span id="password_err" class="err_msg" style="display: none">密码格式有误span>
                td>
            tr>


            <tr>
                <td>验证码td>
                <td class="inputs">
                    <input name="checkCode" type="text" id="checkCode">
                    <img src="imgs/a.jpg">
                    <a href="#" id="changeImg">看不清?a>
                td>
            tr>

        table>

        <div class="buttons">
            <input value="注 册" type="submit" id="reg_btn">
        div>
        <br class="clear">
    form>

div>

<script>
    //1.给用户名输入框绑定一个失去焦点的事件
    document.getElementById("username").onblur = function () {
        //2.发送Ajax请求

        //获取用户名的值
        var username=this.value;


        // 2.1:创建核心对象
        var xhttp;
        if (window.XMLHttpRequest) {
            xhttp = new XMLHttpRequest();
        } else {
            xhttp = new ActiveXObject("Microsoft.XMLHTTP")
        }
        // 2.2:发送请求
        xhttp.open("Get", "http://localhost:8080/ajax-demo/selectUserServlet?username="+username)
        xhttp.send();
        // 2.3:获取响应
        xhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                // alert(this.responseText);

                //    判断
                if (this.responseText=="true"){
                    //用户名存在,显示提示信息
                    document.getElementById("username_err").style.display='';

                }else {
                    //用户名不存在,清除提示信息
                    document.getElementById("username_err").style.display='none';

                }
            }
        }
    }
script>
body>
html>

三、Axios异步框架

JavaWeb—Ajax_第5张图片

JavaWeb—Ajax_第6张图片

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>

<script src="js/axios-0.18.0.js">script>
<script>
    /*axios({
        method:"get",
        url:"http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan"
    }).then(function (resp) {
        alert(resp.data);
    })*/


    /*axios({
        method:"post",
        url:"http://localhost:8080/ajax-demo/axiosServlet",
        data:"username=zhangsan"
    }).then(function (resp) {
        alert(resp.data);
    })*/


    /*axios.get("http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan")
        .then(function (resp) {
        alert(resp.data);
    })*/

    axios.post("http://localhost:8080/ajax-demo/axiosServlet","username=lisi")
        .then(function (resp) {
            alert(resp.data);
        })
script>

body>
html>
package org.example.web.servlet;

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("/axiosServlet")
public class AxiosServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("post....");
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("get....");
        //1.接收参数
        String username = request.getParameter("username");
        System.out.println(username);
        //2.响应数据
        response.getWriter().write("Hello Axios");
    }
}

四、JSON

JavaWeb—Ajax_第7张图片

1.JSON基础语法

JavaWeb—Ajax_第8张图片

2.JSON数据和Java对象相互转换

JavaWeb—Ajax_第9张图片

3.案例

JavaWeb—Ajax_第10张图片

1.查询所有品牌代码

前端页面

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
<a href="addBrand.html"><input type="button" value="新增">a><br>
<hr>
<table id="brandTable" border="1" cellspacing="0" width="100%">

table>


<script src="js/axios-0.18.0.js">script>
<script>
    //1.当页面加载完后,发送Ajax请求
    window.onload=function () {
        //2.发送Ajax请求
        axios({
            method:"get",
            url:"http://localhost:8080/brand-demo1/selectAllServlet"
        }).then(function (resp) {
            //获取数据
            let brands = resp.data;
            let tableData=" \n" +
                "        序号\n" +
                "        品牌名称\n" +
                "        企业名称\n" +
                "        排序\n" +
                "        品牌介绍\n" +
                "        状态\n" +
                "        操作\n" +
                "    "
            for (let i=0;i<brands.length;i++){
                let brand=brands[i];
                tableData +="\n" +
                    "        "+(i+1)+"\n" +
                    "        "+brand.brandName+"\n" +
                    "        "+brand.companyName+"\n" +
                    "        "+brand.ordered+"\n" +
                    "        "+brand.description+"\n" +
                    "        "+brand.status+"\n" +
                    "\n" +
                    "        修改 删除\n" +
                    "    "
            }

            document.getElementById("brandTable").innerHTML=tableData;
        })
    }
script>
body>
html>

控制器代码

package com.itheima.web;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Brand;
import com.itheima.service.BrandService;

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;
import java.util.List;

@WebServlet("/selectAllServlet")
public class SelectAllServlet extends HttpServlet {
    private BrandService brandService=new BrandService();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //设置编码格式
        response.setContentType("text/json;charset=utf-8");
        request.setCharacterEncoding("UTF-8");

        //1.调用service查询
        List<Brand> brands = brandService.selectAll();

        //2.将集合转为JSON数据 序列化
        String jsonString = JSON.toJSONString(brands);

        //3.响应数据
        response.getWriter().write(jsonString);
    }
}

2.添加品牌代码

前端代码

DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>添加品牌title>
head>
<body>
<h3>添加品牌h3>
<form action="" method="post">
    品牌名称:<input id="brandName" name="brandName"><br>
    企业名称:<input id="companyName" name="companyName"><br>
    排序:<input id="ordered" name="ordered"><br>
    描述信息:<textarea rows="5" cols="20" id="description" name="description">textarea><br>
    状态:
    <input type="radio" name="status" value="0">禁用
    <input type="radio" name="status" value="1">启用<br>

    <input type="button" id="btn"  value="提交">
form>

<script src="js/axios-0.18.0.js">script>
<script>
    //1.给按钮绑定事件
    document.getElementById("btn").onclick=function () {
        //将表单数据转为JSON
        var formData={
            brandName:"",
            companyName:"",
            ordered:"",
            description:"",
            status:""
        }

        //获取表单数据
        let brandName = document.getElementById("brandName").value;

        //设置数据
        formData.brandName=brandName;


        let companyName = document.getElementById("companyName").value;
        formData.companyName=companyName;


        let ordered = document.getElementById("ordered").value;
        formData.ordered=ordered;


        let description = document.getElementById("description").value;
        formData.description=description;


        let status = document.getElementsByName("status");
        for (let i=0;i<status.length;i++){
            if (status[i].checked){
                //
                formData.status=status[i].value
            }
        }

        console.log(formData);

        //2.发送Ajax请求
        axios({
            method:"post",
            url:"http://localhost:8080/brand-demo1/addServlet",
            data:formData
        }).then(function (resp) {
            //判断响应数据是否为success
            if (resp.data=="success"){
                location.href="http://localhost:8080/brand-demo1/brand.html"
            }
        })
    }
script>

body>
html>

控制器代码

package com.itheima.web;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Brand;
import com.itheima.service.BrandService;

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.BufferedReader;
import java.io.IOException;

@WebServlet("/addServlet")
public class AddServlet extends HttpServlet {
    private BrandService brandService=new BrandService();

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

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1.接收请求参数, request.getParameter不能接收JSON形式的数据
        /*String brandName = request.getParameter("brandName");
        System.out.println(brandName);*/

        //获取请求体数据
        BufferedReader br = request.getReader();
        String params = br.readLine();

        //将JSON字符串转为Java对象
        Brand brand = JSON.parseObject(params, Brand.class);
        System.out.println(brand);

        //2.调用service方法添加
        brandService.add(brand);

        //3.响应成功标识
        response.getWriter().write("success");
    }
}


总结

遇到的问题:
在axios项目中报错:
GET http://localhost:8080/ajax-demo/js/axios-0.18.0.js net::ERR_ABORTED 404
和 Uncaught ReferenceError: axios is not defined
at 02-axios-demo.html:11:5

应该先将maven项目clean一下

参考视频

你可能感兴趣的:(JavaWeb,ajax,servlet,java)