零基础学JavaWeb开发(十四)之 Ajax

导读:本篇文章讲解 零基础学JavaWeb开发(十四)之 Ajax,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

二十、Ajax

1、axios(ajax)发送请求

ajax概述

Ajax即Asynchronous Javascript And XML(异步JavaScript和XML)在 2005年被Jesse James Garrett提出的新术语,用来描述一种使用现有技术集合的‘新’方法,包括: HTML 或 XHTML, CSS, JavaScript, DOM, XML, XSLT, 以及最重要的XMLHttpRequest。 [3] 使用Ajax技术网页应用能够快速地将增量更新呈现在用户界面上,而不需要重载(刷新)整个页面,这使得程序能够更快地回应用户的操作。

参考 原生ajax:AJAX 简介 | 菜鸟教程

axios 介绍

1.axios 是一个专注于网络请求的库,核心负责发请求和拿数据

在后面的vue react都会用axios来请求数据(类似于后端 httpclient)

2.Axios,是一个基于promise [5] 的网络请求库,作用于node.js浏览器中,它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生node.js http模块, 而在客户端 (浏览端) 则使用XMLHttpRequest。

3.Axios 中文文档 | Axios 中文网 | Axios 是一个基于 promise 的网络请求库,可以用于浏览器和 node.js

axios 发送get/post请求

页面引入axios cdn依赖

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

  // 1. 调用 axios 方法得到的返回值是 Promise 对象
   axios({
     // 请求方式
     method: 'GET',
     // 请求的地址
     url: '接口地址',
     // URL 中的查询参数
     params: {
       id: 1
     }
   }).then(function (result) {
     console.log(result)
   })
<%--
     Created by IntelliJ IDEA.
     User: mayikt
     Date: 2022/6/8
     Time: 15:48
     To change this template use File | Settings | File Templates.
     --%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>axios</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>
        function mayiktAxios() {
            // 1. 调用 axios 方法得到的返回值是 Promise 对象
            axios({
                // 请求方式
                method: 'GET',
                // 请求的地址
                url: 'http://localhost:8080/${pageContext.request.contextPath}/axiosServlet',
                // URL 中的查询参数
                params: {
                    name: "mayikt",
                    age: 22
                }
            }).then(function (result) {
                alert(result.data);
            })

        }
    </script>
</head>
<body>

<input type="button" value="发送ajax" onclick="mayiktAxios()"/>

</body>
</html>

package com.mayikt.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;


@WebServlet("/axiosServlet")
public class AxiosServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter writer = resp.getWriter();
        String name = req.getParameter("name");
        String age = req.getParameter("age");
        writer.print("mayikt,name:" + name + ",age:" + age);
        writer.close();
    }
}

axios验证用户名称是否存在

需求:当我们用户输入用户名称之后(会使用ajax验证用户名称是否已经存在 如果存在的话 则提示 该用户名称是已经存在的)

onkeyup—监听用户输入完内容 走监听方法

package com.mayikt.servlet;

import com.mayikt.entity.MayiktUserEntity;
import com.mayikt.service.MayikUsertService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/exUserNameServlet")
public class ExUserNameServlet extends HttpServlet {
    
    private MayikUsertService mayikUsertService = new MayikUsertService();
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        //1.获取到用户输入的userName参数值
        String userName = req.getParameter("userName");
        //2.调用数据库根据userName查询用户名称是否存在
        MayiktUserEntity mayiktUserEntity = mayikUsertService.findByUserName(userName);
        PrintWriter writer = resp.getWriter();
        if (mayiktUserEntity != null) {
            writer.print("该用户" + userName + "已经存在的 无法注册!");
        }
        writer.close();
    }
}
<%--
  Created by IntelliJ IDEA.
  User: mayikt
  Date: 2022/6/6
  Time: 17:12
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <title>注册页面</title>
    <form action="/mayikt_session_war_exploded/register" method="post">
        <label>用户名: </label><input type="text" name="userName" onkeyup="mayiktAxios(this)"/><br>
        <label>密&nbsp&nbsp&nbsp码: </label><input type="password" name="userPwd"/><br>
        <label>验证码: </label><input type="text" name="code"/><img id="exchangecode" src="VerifycodeServlet">
        <a id="ecode" href="#">看不清?换一张图片</a><br>
        <span id="error" style="color: red">${errorMsg}</span>
        <input type="submit" value="注册"/>
    </form>
    <script type="text/javascript">
        window.onload = function () {
            //获取img标签的对象
            img = document.getElementById("exchangecode");
            img.onclick = function () {
                //加时间戳,避免浏览器缓存
                var date = new Date().getTime()
                img.src = "VerifycodeServlet?" + date;
            }
            //获取a标签的对象
            ec = document.getElementById("ecode");
            ec.onclick = function () {
                //加时间戳
                var date = new Date().getTime()
                img.src = "VerifycodeServlet?" + date;
            }
        }

    </script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>
        function mayiktAxios(object) {
            // 1.接受用户输入的userName
            var userName = object.value;
            // 2.使用Axios 发送ajax请求验证 userName是否存在的
            axios({
                // 请求方式
                method: 'GET',
                // 请求的地址
                url: 'http://localhost:8080${pageContext.request.contextPath}/exUserNameServlet',
                // URL 中的查询参数
                params: {
                    userName: userName,
                }
            }).then(function (result) {
                //定位 span  id 名称 error 修改
                document.getElementById("error").innerText = result.data;
            })
        }
    </script>
</head>
</html>

2、json

json基础语法

JSON: JavaScript Object Notation(JavaScript 对象表示法);

JSON 是存储和交换文本信息的语法。类似 XML;

JSON —数据交换格式

客户端与服务器端之间通讯 —数据交换格式

JSON 体积XML 更小减少带宽传输

JSON 比 XML 更小、更快,更易解析;

json对象

{

name:”mayikt”,

age:22,

isFlag:true

}

如果该json值是为最后一个的情况下 不需要写,

json数组

[

{

name:”mayikt1″,

age:22,

isFlag:true

},

{

name:”mayikt2″,

age:22,

isFlag:true

}

]

{

code:200,

msg:”ok”,

data:[

{

name:”mayikt2″,

age:22,

isFlag:true

},

{

name:”mayikt2″,

age:22,

isFlag:true

}

]

}

1、JSON是由键值对构成的;

2、键要用引号(单双都行)引起,也可以不引;

3、取值范围:

数字(整数或浮点数)

字符串(在双引号中)

逻辑值(true 或 false)

数组(在中括号中)

对象(在大括号中)

null,不常用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jsonDemo</title>
    <script>
        // 1.定义json
        var json1 = {name: "mayikt", age: 22, isFlag: true};
        alert(json1.name);
        alert(json1.age);
        alert(json1.isFlag);
        // 2.定义json数组
        var jsonArr = {code: 200, data: [{name: "mayikt", age: 22}, {name: "meite", age: 22}]};
        alert(jsonArr.code);
        alert(jsonArr.data[0].name);
        var userArr = jsonArr.data;
        for (var i = 0; i < userArr.length; i++) {
            alert(userArr[i].name + "," + userArr[i].age);
        }
    </script>
</head>
<body>

</body>
</html>

fastjson用法

常见解析器:JsonLib,Gson,fastjson(阿里),jackson(Spring MVC内置解析器)

文档:javaweb开发相关资料下载.notea

链接:有道云笔记

零基础学JavaWeb开发(十四)之 Ajax

package com.mayikt;

import com.alibaba.fastjson.JSONObject;
import com.mayikt.entity.MayiktUserEntity;

import java.util.ArrayList;


public class Test01 {
    public static void main(String[] args) {
        //1.将数据对象变成json(字符串类型)
        MayiktUserEntity user1 = new MayiktUserEntity(1, "mayikt", "mayikt");
        MayiktUserEntity user2 = new MayiktUserEntity(1, "mayikt", "mayikt");
        String json1 = JSONObject.toJSONString(user1);
        System.out.println(json1);
        //2.嵌套json
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 200);
        jsonObject.put("msg", "ok");
        //data值 数组类型
        ArrayList<MayiktUserEntity> mayiktUserEntities = new ArrayList<>();
        mayiktUserEntities.add(user1);
        mayiktUserEntities.add(user2);
        jsonObject.put("data", mayiktUserEntities);
        System.out.println(jsonObject.toJSONString());
    }
}
package com.mayikt;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.mayikt.entity.MayiktUserEntity;


public class Test02 {
    public static void main(String[] args) {
        String jsonStr = "{\"msg\":\"ok\",\"code\":200,\"data\":[{\"id\":1,\"userName\":\"mayikt\",\"userPwd\":\"mayikt\"},{\"id\":1,\"userName\":\"mayikt\",\"userPwd\":\"mayikt\"}]}";
        // string类型-----jsonobject----jsonobject
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
//        Integer code = (Integer) jsonObject.get("code");
        Integer code = jsonObject.getInteger("code");
        String msg = jsonObject.getString("msg");
        System.out.println(code + "," + msg);
        JSONArray data = jsonObject.getJSONArray("data");
        for (int i = 0; i < data.size(); i++) {
            JSONObject object = (JSONObject) data.get(i);
            Integer id = object.getInteger("id");
            String userName = object.getString("userName");
            String userPwd = object.getString("userPwd");
            MayiktUserEntity mayiktUserEntity = new MayiktUserEntity(id, userName, userPwd);
            System.out.println(mayiktUserEntity);
        }
    }
}
package com.mayikt;

import com.alibaba.fastjson.JSONObject;
import com.mayikt.entity.Result;


public class Test03 {
    public static void main(String[] args) {
        String jsonStr = "{\"msg\":\"ok\",\"code\":200,\"data\":[{\"id\":1,\"userName\":\"mayikt\",\"userPwd\":\"mayikt\"},{\"id\":1,\"userName\":\"mayikt\",\"userPwd\":\"mayikt\"}]}";
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        Result result = JSONObject.parseObject(jsonStr, Result.class);
        // java序列化技术 将 json变成对象
        System.out.println(result);
    }
}
package com.mayikt.entity;

import java.util.List;

public class Result {
    private Integer code;
    private String msg;
    private List<MayiktUserEntity> data;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }


    public List<MayiktUserEntity> getData() {
        return data;
    }

    public void setData(List<MayiktUserEntity> data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "Result{" +
                "code=" + code +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}';
    }
}
    axios({
        method: "post",
        url: "${pageContext.request.contextPath}/user/addUser",
        data: JSON.stringify(userList),
        headers: {
            'Content-Type': 'application/json;charset=UTF-8'
        }
    }).then(resp => {

    })

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/111830.html

(0)
Java光头强的头像Java光头强

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!