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

二十、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依赖



  // 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" %>


    axios
    
    








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" %>



    注册页面
    


看不清?换一张图片
${errorMsg}

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,不常用




    
    jsonDemo
    




fastjson用法

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

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

链接:有道云笔记

零基础学JavaWeb开发(十四)之 Ajax_第1张图片

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 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 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 getData() {
        return data;
    }

    public void setData(List 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 => {

    })

你可能感兴趣的:(JavaWeb,Java,ajax,javascript,前端,java,web)