12.Ajax

AJAX

笔记目录:(https://www.cnblogs.com/wenjie2000/p/16378441.html)

视频教程(P138~P145)

参考网站:https://www.w3school.com.cn/js/js_ajax_intro.asp

  • 概念:AJAX(Asynchronous JavaScript And XML):异步的JavaScript和XML

  • AJAX作用:

    1. 与服务器进行数据交换:通过AJAX可以给服务器发送请求,并获取服务器响应的数据

      使用了AJAX和服务器进行通信,就可以使用HTML+AJAX来替换JSP页面了

    2. 异步交互:可以在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页的技术,如:搜索联想、用户名是否可用校验,等等...

同步和异步

AJAX快速入门

下面的会正常使用就行,不需要背,后面有简化的写法。

  1. 编写AjaxServlet,并使用response输出字符串

    response.getWriter().write("hello ajax");
    
  2. 创建XMLHttpRequest 对象:用于和服务器交换数据

    var xhttp;
    if (window.XMLHttpRequest) {
        xhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    
  3. 向服务器发送请求

    xhttp.open("GET", "http://localhost:8080/login-web/ajaxServlet");//注意这里的路径是完整路径
    xhttp.send();//发送请求
    
  4. 获取服务器响应数据

    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            alert(this.responseText);
        }
    };
    

案例

使用AJAX验证用户名是否存在

需求:在完成用户注册时,当用户名输入框失去焦点时,校验用户名是否在数据库已存在

package com.itwen.web;

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 {
        //
        String username = request.getParameter("username");
        boolean flag=true;//这里只是要看效果,就只简单模拟情况
        if ("zhangsan".equals(username)){
            flag=false;
        }
        response.getWriter().write(""+flag);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/login-web/registerServlet" method="post">
    用户名:<br><input name="username" id="username">
    <span id="username_err" style="display: none">用户名已存在</span><br>
    密码:<br><input type="password" name="password"><br>
    验证码:<br><input name="checkCode"><img id="checkCodeImg" src="/login-web/checkCodeServlet"><br>
    <input type="submit" value="注册">
</form>
<script>
    //给用户输入框绑定失去焦点事件
    document.getElementById("username").onblur=function () {
        var username=this.value;//获取用户名的值
        var xhttp;
        if (window.XMLHttpRequest) {
            xhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xhttp.open("GET", "http://localhost:8080/login-web/selectUserServlet?username="+username);
        xhttp.send();
        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异步框架

Axios快速入门

  1. 引入axios的js文件

    <script src="js/axios.min.js"></script>
    //也可以使用 unpkg CDN:
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    
  2. 使用axios 发送请求,并获取响应结果

    axios({
        method: "get",
        url: "http://localhost:8080/login-web/ajaxServlet?username=zhangsan"
    }).then(function(response){
        alert(response.data)
    })
    
    axios({
        method: "post",
        url: "http://localhost:8080/login-web/ajaxServlet",
        data:"username=zhangsan"
    }).then(function(response){
        alert(response.data)
    })
    

Axios请求方式别名

  • 为了方便起见,Axios已经为所有支持的请求方法提供了别名。

    axios.request(config)
    
    axios.get(url[, config])
    
    axios.delete(url[, config])
    
    axios.head(url[, config])
    
    axios.options(url[, config])
    
    axios.post(url[, data[, config]])
    
    axios.put(url[, data[, config]])
    
    axios.patch(url[, data[, config]])
    
  • 发送get请求

    axios.get("url").then(function(response){
        alert(response.data);
    });
    
  • 发送post请求

    axios.post("url","data参数").then(function(response){
        alert(response.data);
    });
    

简化方式书写较为简单,但可读性相较于之前的要差一些(两种都可以用,看自己喜好)

JSON

  • 概念:JavaScript Object Notation。JavaScript 对象表示法
  • 由于其语法简单,层次结构鲜明,现多用于作为数据载体,在网络中进行数据传输

JSON基础语法

  • 定义

    var 变量名 = {"key1":value1,
               "key2":value2,
               ...
              };
    

    value的数据类型为:

    数字(整数或浮点数)

    字符串(在双引号中)

    逻辑值(true或false)

    数组(在方括号中)

    对象(在花括号中)

    null

    示例:

    var json = {"name":"zhangsan",
                "age":23,
                "addr":["背景","上海","西安"]
               };
    
  • 获取数据:

    变量名.key
    

    例:

    json.name
    

JSON数据和Java对象转换

  • 请求数据:JSON字符串转为Java对象

  • 响应数据:Java对象转为JSON字符串

  • Fastjson是阿里巴巴提供的一个Java语言编写的高性能功能完善的JSON库,是目前Java语言中最快的JSON库,可以实现Java对象和JSON字符串的相互转换。

  • 使用:

    1. 导入坐标

      <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>fastjson</artifactId>
          <version>1.2.62</version>
      </dependency>
      
    2. Java对象转JSON

      String jsonStr = JSON.toJSONString(obj);
      
    3. JSON字符串转Java对象(注意:字符串为数组对象)

      User user = JSON.parseObject(jsonStr,User.class);
      

案例

查询所有品牌信息

本质就是对于之前的查询品牌数据的改写。将jsp改为html。数据信息改用json传递

我就只给brand.html和web层。其他部分之前写过,这里就不再给了。

package com.itwen.web;

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

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

@WebServlet("/SelectAllServlet2")
public class SelectAllServlet2 extends HttpServlet {
    private BrandService service = new BrandService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.调用BrandService完成查询
        List<Brand> brands = service.selectAll();
        String s = JSON.toJSONString(brands);
        System.out.println(s);
        response.setContentType("text/json;charset=utf-8");//注意要告诉浏览器发送的数据类型
        response.getWriter().write(s);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<table border="1" id="brandTable">
    <tr align="center">
        <td>序号</td>
        <td>品牌名称</td>
        <td>企业名称</td>
        <td>排序</td>
        <td>品牌介绍</td>
        <td>状态</td>
        <td>操作</td>
    </tr>

</table>
<script src="js/axios.min.js"></script>
<script>
    window.onload=function () {
        axios({
            method:"get",
            url:"http://localhost:8080/login-web/SelectAllServlet2",
        }).then(function (response) {
            let brands = response.data;
            let tableDate = "    <tr align=\"center\">\n" +
                "        <td>序号</td>\n" +
                "        <td>品牌名称</td>\n" +
                "        <td>企业名称</td>\n" +
                "        <td>排序</td>\n" +
                "        <td>品牌介绍</td>\n" +
                "        <td>状态</td>\n" +
                "        <td>操作</td>\n" +
                "    </tr>";
            for (let i=0;i<brands.length;i++){
                let brand=brands[i];
                tableDate+="    <tr align=\"center\">\n" +
                    "        <td>"+(i+1)+"</td>\n" +
                    "        <td>"+brand.brandName+"</td>\n" +
                    "        <td>"+brand.companyName+"</td>\n" +
                    "        <td>"+brand.ordered+"</td>\n" +
                    "        <td>"+brand.description+"</td>\n" +
                    "        <td>"+brand.status+"</td>\n" +
                    "        <td><a href=\"#\">修改</a> <a href=\"#\">删除</a></td>" +
                    "    </tr>"
            }
            document.getElementById("brandTable").innerHTML=tableDate;
        })
    }
</script>
</body>
</html>

新增品牌

这里试着自己做,我就不给代码了

需要注意,服务器端获取浏览器发送的json数据不能用之前的request.getParameter(""),获取不到数据(因为不符合以往的get和post的数据规范)。应该直接使用request.getReader()获取字符输入流。再使用readLine()获取请求体中的json字符串。再使用JSON.parseObject(jsonStr,User.class)将字符串转换为java对象。

BufferedReader br = request.getReader();
String params = br.readLine();
User user = JSON.parseObject(params, User.class);//此处的User为举例,实际情况替换成对应的pojo
posted @ 2023-01-09 09:06  文杰2000  阅读(23)  评论(0编辑  收藏  举报