Ajax(Asynchronous Javascript And XML)=异步的 javascript 和XML ,使网页在不重新加载整个页面的情况下,对页面的局部进行刷新,传统的网页(若不使用AJAX)在打开页面时,是需要加载出此页面所有的内容。Ajax是一种新的思想, 是与服务器交换数据并更新网页局部的艺术。
使用JavaScript获取浏览器XMLHttpRequest内置对象,Ajax的核心。
let xml=new XMLHttpRequest();
建立连接方式与请求内容:open()方法,有三个参数,第一个参数为请求方式,第二个参数为请求的路径,第三个参数为对请求是否为异步处理。
xml.open("get","queryUserInfo",true);
设置事件句柄,回调函数
xml.onreadystatechange=function(){
/*
readyState ==0:request未初始化(调用open()之前)
readyState ==1:request已提出(调用send()之前)
readyState ==2:request已发送
readyState ==3:request正在处理中(服务器还未完成响应)
readyState ==4:判断request已完成(可以访问服务器)
status==200:判断request是否执行成功
status==404:表示“Not Found”
*/
if(xml.readyState==4&&xml.status==200){
}
发送数据
xml.send(null);//以get方式提交,以post方式提交时,需要指定需要传送的参数
前提,搭建maven项目,加载Tomcat,添加依赖。
pom.xml,添加依赖,将依赖添加到dependencies当中
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>4.0.1version>
<scope>providedscope>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.75version>
dependency>
user实体类
package com.ajax.model;
public class User {
private int userId;
private String userName;
private String userSex;
private int userAge;
private String userTel;
private String userAddress;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserSex() {
return userSex;
}
public void setUserSex(String userSex) {
this.userSex = userSex;
}
public int getUserAge() {
return userAge;
}
public void setUserAge(int userAge) {
this.userAge = userAge;
}
public String getUserTel() {
return userTel;
}
public void setUserTel(String userTel) {
this.userTel = userTel;
}
public String getUserAddress() {
return userAddress;
}
public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
}
}
servlet,查询所有user信息(queryUserInfo)
package com.ajax.servlet;
import com.ajax.model.User;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/queryUserInfo")
public class QueryUserInfo extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置数据的格式为json
response.setContentType("json/application;charset=utf-8");
List<User> list=new ArrayList<>();
//添加user信息
for(int i = 1;i < 10;i++){
User user=new User();
user.setUserId(100 + i);
user.setUserName("张三"+i);
user.setUserSex(i % 2 == 0 ? "男" : "女");
user.setUserAge(18 + i);
user.setUserTel("1809233094" + i);
user.setUserAddress("西安");
list.add(user);
}
//转为json数组
JSONArray json =(JSONArray) JSONObject.toJSON(list);
//响应给浏览器
PrintWriter pw =response.getWriter();
pw.print(json);
System.out.println(json);
}
}
index.html
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AjaxDemotitle>
<link rel="shortcut icon" href="img/fire.png" type="image/x-icon">
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css" type="text/css">
<script src="bootstrap/js/bootstrap.js" type="text/javascript">script>
<script src="./js/jquery-3.5.1.min.js">script>
<script src="./js/show.js">script>
<style>
.box{
width: 80%;
margin: 15vh auto;
}
table{
text-align: center;
}
table th{
text-align: center;
}
style>
head>
<body>
<div class="box">
<table class="table table-striped table-bordered table-hover table-condensed">
<thead>
<tr>
<th>IDth>
<th>用户名th>
<th>性别th>
<th>年龄th>
<th>电话th>
<th>城市th>
tr>
thead>
<tbody id="userData">
tbody>
table>
div>
body>
html>
js原生,外部引用 show.js
// 使用ajax动态获取表格数据
window.onload = function (){
//1创建XMLHttpRequest对象
let xml=new XMLHttpRequest();
//建立连接
xml.open("get","queryUserInfo",true);
//设置回调函数
xml.onreadystatechange=function(){
/*
readyState ==4:判断request已完成(可以访问服务器)
status==200:判断request是否执行成功
*/
if(xml.readyState==4&&xml.status==200){
//获取到响应数据
let vals = xml.responseText;
//控制台打印
console.log(vals);
//转为json格式
let jsonArr=eval(vals);
//tbody填入数据
let temp = '';
//获取tbody标签
let tbody=document.getElementById("userData");
for(let user of jsonArr){
temp +=
'' +
'' + user.userId + ' ' +
'' + user.userName + ' ' +
'' + user.userSex + ' ' +
'' + user.userAge + ' ' +
'' + user.userTel + ' ' +
'' + user.userAddress + ' ' +
' ';
}
tbody.innerHTML = temp;
}
}
//发送数据
xml.send(null);
}
1)前言:jQuery入口函数的几种书写方式
2)jQuery经过封装,将ajax封装了,使用起来就比较简单了$.ajax()
返回其创建的XMLHttpRequest对象。
常用参数
$.ajax()写法一
$(document).ready(function (){
//获取tbody
let userData = $("#userData");
let temp = '';
$.ajax({
//请求路径servlet
url: "queryUserInfo",
type: "get",
dataType: "json",
async: true,//是否异步
//请求成功
success: function (msg){
let users = msg;
userData.empty();//清空
for (let i = 0; i < users.length; i++) {
temp +=
'' +
'' + users[i].userId + ' ' +
'' + users[i].userName + ' ' +
'' + users[i].userSex + ' ' +
'' + users[i].userAge + ' ' +
'' + users[i].userTel + ' ' +
'' + users[i].userAddress + ' ' +
' ';
}
userData.append(temp);
},
//请求失败
error: function (e) {
alert("request failed !")
}
})
});
$.ajax()写法二
jQuery(document).ready(function () {
let userData = $("#userData");
let temp = '';
$.ajax({
url: "queryUserInfo",
type: "get",
dataType: "json",
async: true,//是否异步
}).done(function (msg){
console.log(JSON.stringify(msg))
let users = msg;
userData.empty();//清空
for (let user of users) {
temp +=
'' +
'' + user.userId + ' ' +
'' + user.userName + ' ' +
'' + user.userSex + ' ' +
'' + user.userAge + ' ' +
'' + user.userTel + ' ' +
'' + user.userAddress + ' ' +
' ';
}
userData.append(temp);
}).fail(function (e){
alert("request failed !")
})
});
$.post()写法:
语法:$.post(url,data,callback,dataType)
$(function () {
$.post("queryUserInfo",function (msg){
console.log(JSON.stringify(msg))
$('#userData').empty();
let temp = '';
for (let user of msg) {
temp +=
'' +
'' + user.userId + ' ' +
'' + user.userName + ' ' +
'' + user.userSex + ' ' +
'' + user.userAge + ' ' +
'' + user.userTel + ' ' +
'' + user.userAddress + ' ' +
' ';
}
$('#userData').append(temp);
})
})
jQuery.get()与上面的$.post()写法相同,只是不一样的请求方式
语法:$.get(URL,callback);
区别:
GET 基本上用于从服务器获得(取回)数据。注释:GET 方法可能返回缓存数据。
POST 也可用于从服务器获取数据。不过,POST 方法不会缓存数据,并且常用于连同请求一起发送数据。