传统请求及缺点
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>传统请求</title>
</head>
<body>
<a href="old/request"></a>
<form action="" method="get">
<input type="button" name="" value="form提交">
</form>
<input type="button" name="" id="" value="提交">
<script>
let btn=addEventListener('click',function () {
window.location.href='/old/request';
})
</script>
</body>
</html>
package A;
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;
@WebServlet("/request")
public class aaa extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
PrintWriter writer = resp.getWriter();
writer.print("欢迎学习");
}
}
AJAX概述
XMLHttpRequest对象
XMLHttpRequest对象的方法
XMLHttpRequest对象的属性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>传统请求</title>
</head>
<body>
<!--<div id="mydiv"></div>-->
<!--<form action="ajaxrequest" method="post">-->
<input type="text" value="">
<input type="submit" value="提交" id="hellobtn">
<!--</form>-->
<script>
window.onload = () => {
document.getElementById("hellobtn").addEventListener("click", () => {
// console.log("ajax")
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
alert(xhr.responseText);
}
}
xhr.open("POST", "ajaxrequest", true);
xhr.send();
}
)
}
// let xhr = new XMLHttpRequest();
// xhr.onreadystatechange = function () {
// if (xhr.readyState === 4 && xhr.status === 404) {
// console.log("hajsa");
// }
// }
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>发送ajax get请求</title>
</head>
<body>
<script type="text/javascript">
window.onload = function () {
document.getElementById("btn").onclick = function () {
//1. 创建AJAX核心对象
var xhr = new XMLHttpRequest();
//2. 注册回调函数
xhr.onreadystatechange = function(){
if (this.readyState == 4) {
if (this.status == 200) {
// 通过XMLHttpRequest对象的responseText属性可以获取到服务器响应回来的内容。
// 并且不管服务器响应回来的是什么,都以普通文本的形势获取。(服务器可能响应回来:普通文本、XML、JSON、HTML...)
// innerHTML属性是javascript中的语法,和ajax的XMLHttpRequest对象无关。
// innerHTML可以设置元素内部的HTML代码。(innerHTML可以将后面的内容当做一段HTML代码解释并执行)
//document.getElementById("myspan").innerHTML = this.responseText
document.getElementById("mydiv").innerHTML = this.responseText
// innerText也不是AJAX中的,是javascript中的元素属性,和XMLHttpRequest无关。
// innerText也是设置元素中的内容,但是即使后面是一段HTML代码,也是将其看做一个普通字符串设置进去。
//document.getElementById("myspan").innerText = this.responseText
}else{
alert(this.status)
}
}
}
//3. 开启通道
xhr.open("GET", "/ajax/ajaxrequest2", true)
//4. 发送请求
xhr.send()
}
}
</script>
<button id="btn">发送ajax get请求</button>
<span id="myspan"></span>
<div id="mydiv"></div>
</body>
</html>
package com.bjpowernode.ajax.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;
/**
* @program: 代码
* @ClassName: AjaxRequest2Servlet
* @version: 1.0
* @description:
* @author: bjpowernode
* @create: 2022-05-13 10:46
**/
@WebServlet("/ajaxrequest2")
public class AjaxRequest2Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置响应的内容类型以及字符集
response.setContentType("text/html;charset=UTF-8");
// 获取响应流
PrintWriter out = response.getWriter();
// 响应
out.print("<font color='red'>用户名已存在!!!</font>");
}
}
AJAX Get请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" id="myinput">
<input type="submit" id="mybtn">
<span>hahhahaha</span>
<script>
let btn=document.querySelector("#mybtn")
btn.addEventListener("click",()=>{
let xhr=new XMLHttpRequest()
xhr.onreadystatechange=()=>{
if(xhr.readyState==4&&xhr.status==200){
let spanElement = document.querySelector("span");
spanElement.innerHTML=xhr.responseText;
// alert(xhr.responseText)
}
}
xhr.open("get","ajaxrequest?username=lisi&age=18",true)
xhr.send()
})
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" id="uname">
<input type="text" id="age">
</input>
<input type="submit" id="mybtn">
<span>hahhahaha</span>
<script>
let btn=document.querySelector("#mybtn")
btn.addEventListener("click",()=>{
let xhr=new XMLHttpRequest()
xhr.onreadystatechange=()=>{
if(xhr.readyState==4&&xhr.status==200){
let spanElement = document.querySelector("span");
spanElement.innerHTML=xhr.responseText;
// alert(xhr.responseText)
}
}
let value = document.getElementById("uname").value;
let age = document.getElementById("age").value;
xhr.open("get","ajaxrequest?username="+value+"&age="+age,true)
xhr.send()
})
</script>
</body>
</html>
AJAX GET请求的缓存问题
AJAX POST请求
package A;
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;
@WebServlet("/ajaxrequest")
public class aaa extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
PrintWriter writer = resp.getWriter();
// writer.print("学习");
String username = req.getParameter("username");
String age = req.getParameter("age");
writer.print("姓名:"+username+"年龄:"+age);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" id="uname" name="username">姓名
<br>
<input type="text" id="age" name="agee"> 年龄
<br>
<input type="submit" id="mybtn">
<br>
<span class="iii">hahhahaha</span>
<script>
let btn = document.querySelector("#mybtn");
btn.addEventListener("click", () => {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState == 4 && xhr.status == 200) {
let spanElement = document.querySelector(".iii");
spanElement.innerHTML = xhr.responseText;
}
}
xhr.open("post", "ajaxrequest", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
let value = document.getElementById("uname").value;
let age = document.getElementById("age").value;
xhr.send("username="+value+"&age="+age);
}
)
</script>
</body>
</html>
案例
基于JSON的数据交换
eg:把数据库的数据拼接成json格式,如果拼接的话太痛苦了。用架包
基于XML的数据交换
package com.bjpowernode.ajax.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;
/**
* @program: 代码
* @ClassName: AjaxRequest6Servlet
* @version: 1.0
* @description: 服务器端返回XML字符串
* @author: bjpowernode
* @create: 2022-05-15 11:48
**/
@WebServlet("/ajaxrequest6")
public class AjaxRequest6Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 注意:响应的内容类型是XML。
response.setContentType("text/xml;charset=UTF-8");
PrintWriter out = response.getWriter();
/*
<students>
<student>
<name>zhangsan</name>
<age>20</age>
</student>
<student>
<name>lisi</name>
<age>22</age>
</student>
</students>
*/
StringBuilder xml = new StringBuilder();
xml.append("<students>");
xml.append("<student>");
xml.append("<name>zhangsan</name>");
xml.append("<age>20</age>");
xml.append("</student>");
xml.append("<student>");
xml.append("<name>lisi</name>");
xml.append("<age>22</age>");
xml.append("</student>");
xml.append("</students>");
out.print(xml);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>使用XML完成数据交换</title>
</head>
<body>
<script type="text/javascript">
window.onload = function(){
document.getElementById("btn").onclick = function(){
// 1.创建XMLHTTPRequest对象
var xhr = new XMLHttpRequest();
// 2.注册回调函数
xhr.onreadystatechange = function () {
if (this.readyState == 4) {
if (this.status == 200) {
// 服务器端响应了一个XML字符串,这里怎么接收呢?
// 使用XMLHTTPRequest对象的responseXML属性,接收返回之后,可以自动封装成document对象(文档对象)
var xmlDoc = this.responseXML
//console.log(xmlDoc)
// 获取所有的<student>元素,返回了多个对象,应该是数组。
var students = xmlDoc.getElementsByTagName("student")
//console.log(students[0].nodeName)
var html = "";
for (var i = 0; i < students.length; i++) {
var student = students[i]
// 获取<student>元素下的所有子元素
html += "<tr>"
html += "<td>"+(i+1)+"</td>"
var nameOrAge = student.childNodes
for (var j = 0; j < nameOrAge.length; j++) {
var node = nameOrAge[j]
if (node.nodeName == "name") {
//console.log("name = " + node.textContent)
html += "<td>"+node.textContent+"</td>"
}
if (node.nodeName == "age") {
//console.log("age = " + node.textContent)
html += "<td>"+node.textContent+"</td>"
}
}
html += "</tr>"
}
document.getElementById("stutbody").innerHTML = html
}else{
alert(this.status)
}
}
}
// 3.开启通道
xhr.open("GET", "/ajax/ajaxrequest6?t=" + new Date().getTime(), true)
// 4.发送请求
xhr.send()
}
}
</script>
<button id="btn">显示学生列表</button>
<table width="500px" border="1px">
<thead>
<tr>
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody id="stutbody">
<!--<tr>
<td>1</td>
<td>zhangsan</td>
<td>20</td>
</tr>
<tr>
<td>2</td>
<td>lisi</td>
<td>22</td>
</tr>-->
</tbody>
</table>
</body>
</html>
AJAX乱码问题
package A;
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;
@WebServlet("/ajaxrequest")
public class aaa extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
String user = req.getParameter("user");
PrintWriter writer = resp.getWriter();
writer.print(user);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// req.setCharacterEncoding("UTF-8");
String user = req.getParameter("user");
PrintWriter writer = resp.getWriter();
writer.print(user);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" id="myinput">
<br>
<div id="mydiv">1111</div>
<br>
<button id="mybtn1">提交get</button>
<br>
<button id="mybtn2">提交post</button>
<script>
let mybtn1 = document.getElementById("mybtn1");
mybtn1.addEventListener("click",()=>{
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if(xhr.status==200){
document.querySelector("#mydiv").innerHTML=xhr.responseText;
}
}
}
let user = document.getElementById("myinput").value;
// xhr.open("GET", "ajaxrequest?user"+user+"&t="+new Date().getTime(), true)
xhr.open("GET", "ajaxrequest?user="+user+"&t=" + new Date().getTime(), true);
xhr.send();
})
let mybtn2 = document.getElementById("mybtn2");
mybtn2.addEventListener("click",()=>{
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
document.querySelector("#mydiv").innerHTML=xhr.responseText;
}
}
xhr.open("post", "ajaxrequest?", true)
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
let user = document.querySelector("#myinput").value;
xhr.send("user="+user);
})
</script>
</body>
</html>
AJAX的异步与同步
什么是异步?什么是同步?
异步和同步在代码上如何实现?
AJAX代码封装
function jQuery(selector){
if (typeof selector == "string") {
if (selector.charAt(0) == "#") {
domObj = document.getElementById(selector.substring(1))
return new jQuery()
}
}
if (typeof selector == "function") {
window.onload = selector
}
this.html = function(htmlStr){
domObj.innerHTML = htmlStr
}
this.click = function(fun){
domObj.onclick = fun
}
this.focus = function (fun){
domObj.onfocus = fun
}
this.blur = function(fun) {
domObj.onblur = fun
}
this.change = function (fun){
domObj.onchange = fun
}
this.val = function(v){
if (v == undefined) {
return domObj.value
}else{
domObj.value = v
}
}
// 静态的方法,发送ajax请求
/**
* 分析:使用ajax函数发送ajax请求的时候,需要程序员给我们传过来什么?
* 请求的方式(type):GET/POST
* 请求的URL(url):url
* 请求时提交的数据(data):data
* 请求时发送异步请求还是同步请求(async):true表示异步,false表示同步。
*/
jQuery.ajax = function(jsonArgs){
// 1.
var xhr = new XMLHttpRequest();
// 2.
xhr.onreadystatechange = function(){
if (this.readyState == 4) {
if (this.status == 200) {
// 我们这个工具类在封装的时候,先不考虑那么多,假设服务器返回的都是json格式的字符串。
var jsonObj = JSON.parse(this.responseText)
// 调用函数
jsonArgs.success(jsonObj)
}
}
}
if (jsonArgs.type.toUpperCase() == "POST") {
// 3.
xhr.open("POST", jsonArgs.url, jsonArgs.async)
// 4.
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
xhr.send(jsonArgs.data)
}
if (jsonArgs.type.toUpperCase() == "GET") {
xhr.open("GET", jsonArgs.url + "?" + jsonArgs.data, jsonArgs.async)
xhr.send()
}
}
}
$ = jQuery
// 这里有个细节,执行这个目的是为了让静态方法ajax生效。
new jQuery()
<script type="text/javascript" src="/ajax/js/jQuery-1.0.0.js"></script>
<script type="text/javascript">
$(function(){
$("#btn1").click(function(){
$.ajax({
type : "POST",
url : "/ajax/ajaxrequest11",
data : "username=" + $("#username").val(),
async : true,
success : function(json){
$("#div1").html(json.uname)
}
})
})
})
</script>
AJAX实现省市联动
AJAX跨域问题
AJAX跨域解决方案
方案1:设置响应头
方案2:jsonp
方案3:jQuery封装的jsonp
方案4:代理机制(httpclient)
方案5:nginx反向代理
AJAX实现搜索联想 自动补全
附录:HTTP状态信息
1xx: 信息
2xx: 成功
3xx: 重定向
4xx: 客户端错误