Asynchronous JavaScript And XML(异步的JavaScript和XML)
Ajax可以在不刷新页面的前提下,进行页面局部更新
Ajax是前端开发的必备技能,也是主流的开发模式
XmlHttpRequest是Ajax的核心,Ajax使用该对象发起请求,接受响应
XmlHttpRequest并不是W3C的标准,不同浏览器的创建方式不同
var xmlhttp;
if (window.XMLHttpRequest) {
//IE7+,Firefox,Chrome,Opera,Safari浏览器执行代码
xmlhttp = new XMLHttpRequest();
} else {
//IE6,IE5浏览器执行代码
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
console.log("XMLHttpRequest:", xmlhttp);
xmlhttp.open()用于创建请求
xmlhttp.send()用于发送请求
// 2.发送Ajax请求
//创建请求
xmlhttp.open("GET", "/content");
//发送到服务器
xmlhttp.send();
xmlhttp.onreadystatechange()事件用于监听Ajax的执行过程
xmlhttp.readyState属性说明XMLHttpRequest当前状态
xmlhttp.status属性服务器响应状态码,200:成功 404:未找到…
// 3.处理服务器响应
xmlhttp.onreadystatechange = function () {
//响应已被接受且服务器处理成功时才执行
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//获取响应体的文本
var t = xmlhttp.responseText;
//对服务器结果进行处理
console.log(t);
document.getElementById("divContent").innerHTML = t;
}
};
@WebServlet("/content")
public class ContentServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().println("I am content");
}
}
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<input id="btnLoad" type="button" value="加载"/>
<div id="divContent">div>
<script>
document.getElementById("btnLoad").onclick = function () {
// 1.创建XmlHttpRequest对象
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
console.log("XMLHttpRequest:", xmlhttp);
// 2.发送Ajax请求
xmlhttp.open("GET", "/content");
xmlhttp.send();
// 3.处理服务器响应
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var t = xmlhttp.responseText;
console.log(t);
document.getElementById("divContent").innerHTML = t;
}
};
}
script>
body>
html>
JavaScript Object Notation(JavaScript对象表示法)
JSON是轻量级的文本数据交换格式
JSON独立于语言,具有自我描述性,更容易理解
数据由键(key)/值(value)描述,由冒号分隔
大括号代表一个完整的对象,拥有多个键/值对
中括号保存数组,多个对象之间使用逗号分隔
创建employ.json
[
{
"empno": 7369,
"ename": "李宁",
"job": "软件工程师"
},
{
"empno": 7370,
"ename": "张三",
"job": "客户经理",
"customers": [
{
"cname": "李东"
},
{
"cname": "李四"
}
]
}
]
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script>
var employeeList = [
{
"empno": 7369,
"ename": "李宁",
"job": "软件工程师"
},
{
"empno": 7370,
"ename": "张三",
"job": "客户经理",
"customers": [
{
"cname": "李东"
},
{
"cname": "李四"
}
]
}
];
for (var i = 0; i < employeeList.length; i++) {
var employee = employeeList[i];
console.log(employee);
document.write(""
);
document.write(employee.empno+","+employee.ename+","+employee.job);
document.write("");
if (employee.customers != null) {
document.write(""
);
for (var j = 0; j < employee.customers.length; j++) {
var customer = employee.customers[j];
document.write(customer.cname + ",");
}
document.write("");
}
}
script>
head>
<body>
body>
html>
将java对象转化为标准的json字符串
Jackson是国内外著名的Jaca开源JSON序列化组件
Jackson国内拥有大量使用者,拥有API简单,效率高等优点
Jackson也是众多Java框架的底层组件,掌握Jackson很重要
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.15.2version>
dependency>
点击File中的Project Structure,再点击左侧的Artifacts,将右侧的jar包添加到lib目录下
package com.nuage.ajax.entity;
public class News {
private String title;
private String date;
private String source;
private String content;
public News(String title, String date, String source, String content) {
this.title = title;
this.date = date;
this.source = source;
this.content = content;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
@WebServlet("/news")
public class NewsServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<News> list = new ArrayList<>();
list.add(new News("2018年编程语言排行趋势", "2018-5-1", "tiobe", "..."));
list.add(new News("2019年编程语言排行趋势", "2018-5-1", "tiobe", "..."));
list.add(new News("2020年编程语言排行趋势", "2018-5-1", "tiobe", "..."));
list.add(new News("2021年编程语言排行趋势", "2018-5-1", "tiobe", "..."));
//将Java对象转换为json字符串的核心实现
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(list);
resp.setContentType("text/json;charset=utf-8");
resp.getWriter().println(json);
}
}
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<div id="container">div>
<script>
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
//IE6,IE5浏览器执行代码
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "/news");
xmlhttp.send();
// 3.处理服务器响应
xmlhttp.onreadystatechange = function () {
//响应已被接受且服务器处理成功时才执行
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//获取响应体的文本
var t = xmlhttp.responseText;
//对服务器结果进行处理
console.log(t);
//将字符串转换为JSON
var json = JSON.parse(t);
console.log(json);
for (var i = 0; i < json.length; i++) {
var news = json[i];
var container = document.getElementById("container");
container.innerHTML = container.innerHTML+""
+ news.title+"";
}
}
};
script>
body>
html>
查看下面官网有步骤
axios中文文档|axios中文网 | axios (axios-js.com)
将下面代码或者网站里代码重写写在一个js文件中,写在html中
<script src="https://unpkg.com/axios/dist/axios.min.js">script>
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="/js/axios.js">script>
head>
<body>
<div id="container">div>
<script>
//params传入参数
axios.get("/news", {params:{"t":"pypl"}}).then(function (response) {
console.log(response);
//获取json数据
var json = response.data;
for (var i = 0; i < json.length; i++) {
var news = json[i];
var container = document.getElementById("container");
container.innerHTML = container.innerHTML+""
+ news.title+"";
}
}).catch(function (error) {
console.log(error);
});
script>
body>
html>
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="/js/axios.js">script>
head>
<body>
<div id="container">div>
<script>
//xos为我们提供的请求参数对象
const params = new URLSearchParams();
params.append("t", "pypl");
params.append("1", "abc");
// axios.post("/news", "t=pypl&1=abc",
// {headers:{"content-type":"application/x-www-form-urlencoded"}})
axios.post("/news", params)
.then(function (response) {
console.log(response);
var json = response.data;
for (var i = 0; i < json.length; i++) {
var news = json[i];
var container = document.getElementById("container");
container.innerHTML = container.innerHTML+""
+ news.title+"";
}
}).catch(function (error) {
console.log(error);
});
script>
body>
html>
同步是在服务器未返回JSON前,JS程序一直处于阻塞等待的状态
异步是在服务器未返回JSON前,不阻塞程序,Ajax通过回调获取结果
package com.nuage.ajax.entity;
public class Channel {
private String code;
private String name;
public Channel() {
}
public Channel(String code, String name) {
this.code = code;
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@WebServlet("/channel")
public class ChannelServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String level = req.getParameter("level");
String parent = req.getParameter("parent");
List<Channel> chlist = new ArrayList<>();
if (level.equals("1")) {
chlist.add(new Channel("ai", "人工智能"));
chlist.add(new Channel("web", "前端开发"));
} else if (level.equals("2")) {
if (parent.equals("ai")) {
chlist.add(new Channel("dl", "深度学习"));
chlist.add(new Channel("cv", "计算机视角"));
chlist.add(new Channel("nlp", "自然语言处理"));
} else if (parent.equals("web")) {
chlist.add(new Channel("html", "深度学习"));
chlist.add(new Channel("css", "计算机视角"));
chlist.add(new Channel("js", "自然语言处理"));
}
}
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(chlist);
resp.setContentType("application/json;charset=utf-8");
resp.getWriter().println(json);
}
}
channel.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="/js/axios.js">script>
head>
<body>
<select id="lv1" style="width: 200px;height: 30px">
<option value="-1" selected="selected">请选择option>
select>
<select id="lv2" style="width: 200px;height: 30px">select>
<script>
var lv1 = document.getElementById("lv1");
axios.get("/channel", {params: {"level": 1}})
.then(function (response) {
var json = response.data;
console.log(json);
for (var i = 0; i < json.length; i++) {
var channel = json[i];
lv1.options.add(new Option(channel.name, channel.code));
}
});
var lv2 = document.getElementById("lv2");
lv1.onchange = function () {
axios.get("/channel", {params: {"level": 2, "parent": lv1.value}})
.then(function (response) {
var json = response.data;
console.log(json);
lv2.length = 0;
for (var i = 0; i < json.length; i++) {
var channel = json[i];
lv2.options.add(new Option(channel.name, channel.code));
}
});
}
script>
body>
html>