一、AJAX简介

1.概念

        AJAX(Asynchronous Javascript And XML):异步的JavaScript和XML。

2.作用

(1)AJAX可以与服务器进行数据交换(★)

        通过AJAX可以给服务器发送请求,并获取服务器的响应数据。正因如此HTML+AJAX就可以替换JSP页面了。

(2)异步交互

        可在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页,如:搜索联想(如图)、注册时的用户名存在校验等。
        

二、AJAX的使用

1.服务端代码

        编写AjaxServlet;

2.客户端代码(写在html文件中)

        (w3school可查
(1)创建XMLHttpRequest对象(用于和服务器交换数据):
var xhttp;
if (window.XMLHttpRequest) {
    xhttp = new XMLHttpRequest();
    } else {
    // code for IE6, IE5
     xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
(2)向服务器发送请求
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
【tips】open()方法介绍:
open(method, url, async)

规定请求的类型:

  • method:请求的类型:GET 还是 POST
  • url:服务器(文件)位置
  • async:true(异步)或 false(同步)
(3)获取服务器响应数据
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    alert(this.responseText);
  }
};

三、Axios异步框架(★)

        Axios异步框架实现了对AJAX的封装,简化代码的书写实现ajax与服务器交换数据

1.Axios的使用(写在html中

(1)引入Axios的js文件:

<script src="js/axios-0.18.0.js"></script>

(2)使用axios发送请求并获取响应数据

        1)get

//1.get
axios({
    method:"get",
    url:"http://localhost:8080/ajax_Demo/axiosServlet?username=zhangsan"
}).then(function(resp){
    alert(resp.data);
})

        2)post

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

2.Axios请求方式别名

(1)axios. get (url[, config])
axios.get("http://localhost:8080/ajax_Demo/axiosServlet?username=zhangsan").then(function (resp){
    alert(resp.data);
})
(2)axios. delete (url[, config])
(3)axios. post (url[, data[, config]])
axios.post("http://localhost:8080/ajax_Demo/axiosServlet","username=zhangsan").then(function (resp){
    alert(resp.data);
})
(4)axios. put (url[, data[, config]])
(5)axios. patch (url[, data[, config]])
(6)axios. head (url[, config])
(7)axios. options (url[, config])

四、JSON(★)

        JSON(JavaScript Object Notation):JS对象表示法,其语法简单,层次结构鲜明,现多用于作为数据载体进行数据传输

1.基础语法

(1)定义:键要用""括起来

【tips】value的数据类型可以为:数字(整型或浮点数)、字符串("")、boolean、数组(在[]Java象(在{}中、null。
        示例:

(2)获取数据:使用 变量名.键名 通过键获取值。
         示例:json.name

2.JSON数据和Java对象的转换

(1)为什么要进行二者间的转换?

        服务器接收JSON据转成Java对象,服务器把Java对象转换成JSON数据发送给客户端。

(2)Fastjson(★)

        Fastjson是阿里巴巴提供的一个Java语言编写的高性能、功能完善的JSON库,可以实现JSON数据和Java对象的相互转换。

        1)导入坐标

<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.2.62</version>
</dependency>

        2)Java对象转JSON:toJSONString()方法

String jsonStr = JSON.toJSONString(obj);

        3)JSON转Java对象:parseObject()方法

Object obj = JSON.parseObject(jsonStr,Obj.class);