XMLHttpRequest对象是AJAX的核心对象,发送请求以及接收服务器数据的返回,全靠它了。
XMLHttpRequest对象,现代浏览器都是支持的,都内置了该对象。直接用即可。
创建XMLHttpRequest对象
var xhr = new XMLHttpRequest();
XMLHttpRequest对象的方法
方法 | 描述 |
---|---|
abort() | 取消当前请求 |
getAllResponseHeaders() | 返回头部信息 |
getResponseHeader() | 返回特定的头部信息 |
open(method, url, async, user, psw) | 规定请求method:请求类型 GET 或 POSTurl:文件位置async:true(异步)或 false(同步)user:可选的用户名称psw:可选的密码 |
send() | 将请求发送到服务器,用于 GET 请求 |
send(string) | 将请求发送到服务器,用于 POST 请求 |
setRequestHeader() | 向要发送的报头添加标签/值对 |
属性 | 描述 |
---|---|
onreadystatechange | 定义当 readyState 属性发生变化时被调用的函数 |
readyState | 保存 XMLHttpRequest 的状态。0:请求未初始化 1:服务器连接已建立 2:请求已收到 3:正在处理请求 4:请求已完成且响应已就绪 |
responseText | 以字符串返回响应数据 |
responseXML | 以 XML 数据返回响应数据 |
status | 返回请求的状态号200: "OK"403: "Forbidden"404: “Not Found” |
statusText | 返回状态文本(比如 “OK” 或 “Not Found”) |
发送AJAX get请求,前端代码:
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>
发送AJAX get请求,后端代码:
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("用户名已存在!!!");
}
}
AJAX get请求如何提交数据呢?
AJAX POST请求和GET请求的代码区别在哪里?就是前端代码有区别。后端代码没有区别。
// 4. 发送AJAX POST请求
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded") // 设置请求头的内容类型。模拟form表单提交数据。
// 获取表单中的数据
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
// send函数中的参数就是发送的数据,这个数据在“请求体”当中发送。
xhr.send("username="+username+"&password="+password)
实现一个案例:使用AJAX POST请求实现用户注册的时候,用户名是否可用。(验证用户名是否可以注册)实现步骤如下:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AJAX POST请求验证用户名是否可用title>
head>
<body>
<script type="text/javascript">
window.onload=function (){
document.getElementById("username").onfocus=function (){
document.getElementById("tipMsg").innerHTML=""
}
document.getElementById("username").onblur=function (){
//console.log("正在发送ajax请求")
//1.创建AJAX核心对象
var xhr = new XMLHttpRequest()
//2.注册回调函数
xhr.onreadystatechange=function (){
if(this.readyState==4){
if(this.status==200){
document.getElementById("tipMsg").innerHTML=this.responseText
}else{
alert(this.status)
}
}
}
//3.开启通道
xhr.open("POST","/ajax/ajaxrequest5",true)
//4.发送请求
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
var username = document.getElementById("username").value;
xhr.send("username="+username)
}
}
script>
用户名:<input type="text" id="username">
<span id="tipMsg">span>
body>
html>
package com.jmpower.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;
import java.sql.*;
//验证用户名是否可用
@WebServlet("/ajaxrequest5")
public class AjaxRequest5Servlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取用户名
String username = request.getParameter("username");
//连接数据库验证用户名是否存在
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
boolean exit=false;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn= DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jmpower","root","021107");
String sql="select * from t_user where user=?";
ps=conn.prepareStatement(sql);
ps.setString(1,username);
rs=ps.executeQuery();
if(rs.next()){
exit=true;
}
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print(exit?"对不起,用户名已存在"
:"用户名可以使用");
}
}
实现一个案例:用户点击按钮之后,发送AJAX请求,显示学生列表。
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("myBtn").onclick=function (){
//1.创建核心对象
var xhr = new XMLHttpRequest()
//2.注册回调函数
xhr.onreadystatechange=function (){
if(this.readyState==4){
if(this.status==200){
//var stus=window.eval(this.responseText)//stu是一个数组
var stus = JSON.parse(this.responseText);
var html=""
for(var i=0;i<stus.length;i++){
var stu = stus[i];
html += ""
html += " "+(i+1)+" "
html += " "+stu.name+" "
html += " "+stu.age+" "
html += " "+stu.addr+" "
html += " "
}
document.getElementById("stubody").innerHTML=html
}else{
alert(this.status)
}
}
}
//3.开启通道
xhr.open("GET","/ajax/ajaxrequest6?"+new Date().getTime(),true)
//4.发送请求
xhr.send()
}
}
script>
<input type="button" value="获取学生信息" id="myBtn">
<table width="50%" border="1px">
<tr>
<th>序号th>
<th>姓名th>
<th>年龄th>
<th>住址th>
tr>
<tbody id="stubody">
tbody>
table>
body>
html>
package com.jmpower.ajax.servlet;
import com.alibaba.fastjson.JSON;
import com.jmpower.ajax.bean.Student;
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;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/ajaxrequest6")
public class AjaxRequest6Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
//缺点:后端程序需要编写HTML代码,不好维护
/*StringBuilder s=new StringBuilder();
s.append("");
s.append(" 1 ");
s.append(" 张三 ");
s.append(" 18 ");
s.append(" 山东 ");
s.append(" ");
s.append("");
s.append(" 2 ");
s.append(" 李四 ");
s.append(" 19 ");
s.append(" 北京 ");
s.append(" ");
out.print(s);*/
//将以上程序拼接HTML,换成拼接JSON格式的字符串
//String stu="[{\"user\":\"张三\",\"age\":\"18\",\"addr\":\"山东\"},
// {\"user\":\"李四\",\"age\":\"19\",\"addr\":\"北京\"}]";
//连接数据库,查询所有学生,拼接json字符串
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
boolean exit=false;
//StringBuilder s=new StringBuilder();
String jsonStr="";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn= DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jmpower","root","021107");
String sql="select name,age,addr from t_student";
ps=conn.prepareStatement(sql);
rs=ps.executeQuery();
/*s.append("[");
while(rs.next()){
String name = rs.getString("name");
String age = rs.getString("age");
String addr = rs.getString("addr");
//{"user":" 张三 ","age":" 18 ","addr":" 山东 "},
s.append("{\"user\":\"");
s.append(name);
s.append("\",\"age\":\"");
s.append(age) ;
s.append("\",\"addr\":\"");
s.append(addr);
s.append("\"},");
}
if(s.length()>2){
s.substring(0,s.length());
s.append("]");
}else{
s.append("]");
}*/
List<Student> studentList=new ArrayList<>();
while(rs.next()){
String name = rs.getString("name");
int age = rs.getInt("age");
String addr = rs.getString("addr");
Student student=new Student(name,age,addr);
studentList.add(student);
}
jsonStr= JSON.toJSONString(studentList);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
//响应JSON格式字符串给前端
out.print(jsonStr);
}
}
在WEB前端中,如何将一个json格式的字符串转换成json对象
ascript
var jsonStr = "{\"username\" : \"zhangsan\", \"password\" : \"1233344\"}"
var jsonObj = JSON.parse(jsonStr)
console.log(jsonObj.username)
console.log(jsonObj.password)
在后端拼接JSON格式的字符串,响应给前端的浏览器
json.append("[");
while (rs.next()) {
// 获取每个学生的信息
String name = rs.getString("name");
String age = rs.getString("age");
String addr = rs.getString("addr");
// 拼接json格式的字符串
// {"name":" 王五 ","age": 20 ,"addr":" 北京大兴区 "},
json.append("{\"name\":\"");
json.append(name);
json.append("\",\"age\":");
json.append(age);
json.append(",\"addr\":\"");
json.append(addr);
json.append("\"},");
}
jsonStr = json.substring(0, json.length() - 1) + "]";
拼接JSON格式的字符串太痛苦,可以使用阿里巴巴的fastjson组件,它可以将java对象转换成json格式的字符串
List<Student> studentList = new ArrayList<>();
while (rs.next()) {
// 取出数据
String name = rs.getString("name");
int age = rs.getInt("age");
String addr = rs.getString("addr");
// 将以上数据封装成Student对象
Student s = new Student(name, age, addr);
// 将Student对象放到List集合
studentList.add(s);
}
// 将List集合转换成json字符串
jsonStr = JSON.toJSONString(studentList);
注意:使用fastjson需要引入fastjson-1.2.2.jar
注意:如果服务器端响应XML的话,响应的内容类型需要写成:
response.setContentType("text/xml;charset=UTF-8");
xml和JSON都是常用的数据交换格式
基于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)
// 获取所有的元素,返回了多个对象,应该是数组。
var students = xmlDoc.getElementsByTagName("student")
//console.log(students[0].nodeName)
var html = "";
for (var i = 0; i < students.length; i++) {
var student = students[i]
// 获取元素下的所有子元素
html += ""
html += ""+(i+1)+" "
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 += ""+node.textContent+" "
}
if (node.nodeName == "age") {
//console.log("age = " + node.textContent)
html += ""+node.textContent+" "
}
}
html += " "
}
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">
tbody>
table>
body>
html>
基于XML的数据交换,后端java程序:
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();
/*
zhangsan
20
lisi
22
*/
StringBuilder xml = new StringBuilder();
xml.append("" );
xml.append("" );
xml.append("zhangsan ");
xml.append("20 ");
xml.append("");
xml.append("" );
xml.append("lisi ");
xml.append("22 ");
xml.append("");
xml.append("");
out.print(xml);
}
}
测试内容:
包括还要测试tomcat服务器的版本:
测试结果:
对于tomcat10来说,关于字符集,我们程序员不需要干涉,不会出现乱码。
对于tomcat9来说呢?
响应中文的时候,会出现乱码,怎么解决?
response.setContentType("text/html;charset=UTF-8");
发送ajax post请求的时候,发送给服务器的数据,服务器接收之后乱码,怎么解决?
request.setCharacterEncoding("UTF-8");
什么是异步?什么是同步?
异步和同步在代码上如何实现?
// 假设这个是ajax请求1
// 如果第三个参数是false:这个就表示“ajax请求1”不支持异步,也就是说ajax请求1发送之后,会影响其他ajax请求的发送,只有当我这个请求结束之后,你们其他的ajax请求才能发送。
// false表示,不支持异步。我这个请求发了之后,你们其他的请求都要靠边站。都等着。你们别动呢,等我结束了你们再说。
xhr1.open("请求方式", "URL", false)
xhr1.send()
// 假设这个是ajax请求2
// 如果第三个参数是true:这个就表示“ajax请求2”支持异步请求,也就是说ajax请求2发送之后,不影响其他ajax请求的发送。
xhr2.open("请求方式", "URL", true)
xhr2.send()
什么情况下用同步?(大部分情况下我们都是使用ajax异步方式,同步很少用。)
AJAX请求相关的代码都是类似的,有很多重复的代码,这些重复的代码能不能不写,能不能封装一个工具类。要发送ajax请求的话,就直接调用这个工具类中的相关函数即可。
接下来,手动封装一个工具类,这个工具类我们可以把它看做是一个JS的库。我们把这个JS库起一个名字,叫做jQuery。(我这里封装的jQuery只是一个前端的库,和后端的java没有关系,只是为了方便web前端代码的编写,提高WEB前端的开发效率)
手动开发jQuery,源代码
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>
什么是省市联动?
进行数据库表的设计
t_area (区域表)
id(PK-自增) code name pcode
---------------------------------------------
1 001 河北省 null
2 002 河南省 null
3 003 石家庄 001
4 004 邯郸 001
5 005 郑州 002
6 006 洛阳 002
7 007 丛台区 004
将全国所有的省、市、区、县等信息都存储到一张表当中。
采用的存储方式实际上是code pcode形势。
建表t_area,模拟好数据。
drop table if exists t_area;
create table t_area(
id int primary key auto_increment,
code varchar(255),
name varchar(255),
pcode varchar(255)
);
insert into t_area(code,name,pcode) values('001','河北省',null);
insert into t_area(code,name,pcode) values('002','河南省',null);
insert into t_area(code,name,pcode) values('003','石家庄','001');
insert into t_area(code,name,pcode) values('004','邯郸','001');
insert into t_area(code,name,pcode) values('005','郑州','002');
insert into t_area(code,name,pcode) values('006','洛阳','002');
insert into t_area(code,name,pcode) values('007','山东省',null);
insert into t_area(code,name,pcode) values('008','烟台','007');
ajax12.html:实现前端页面的设计,向后端发送请求查询数据
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>省市联动title>
head>
<body>
<script type="text/javascript" src="/ajax/js/jQuery-1.0.0.js">script>
<script type="text/javascript">
$(function(){
$.ajax({
"type":"GET",
"url":"/ajax/listArea",
"data":"t="+new Date().getTime(),
"async":true,
"success":function(jsonArr){//这是一个json对象数组
//[{"code":"001","name":"河北省"},{"code":"002","name":"河南省"}]
var html = ""
for(var i=0;i<jsonArr.length;i++){
var area=jsonArr[i];
html+="+area.name+""
}
$("#province").html(html)
}
})
//只要change发生,就发送ajax请求
$("#province").change(function(){
$.ajax({
"type":"GET",
"url":"/ajax/listArea",
"data":"t="+new Date().getTime()+"&pcode="+this.value,
"async":true,
"success":function(jsonArr){//这是一个json对象数组
//[{"code":"005","name":"xxx"},{"code":"008","name":"yyyy"}]
var html = ""
for(var i=0;i<jsonArr.length;i++){
var area=jsonArr[i];
html+="+area.name+""
}
$("#city").html(html)
}
})
})
})
script>
<select id="province">
select>
<select id="city">
select>
body>
html>
ListAreaServlet:查询数据库,响应json格式字符串给前端
package com.jmpower.ajax.servlet;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.ClassSerializer;
import com.jmpower.ajax.bean.Area;
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;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/listArea")
public class ListAreaServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String pcode = request.getParameter("pcode");
//连接数据库,获取所有对应信息。最终响应一个JSON格式的字符串给WEB前端
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
List<Area> areaList=new ArrayList<>();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url="jdbc:mysql://127.0.0.1:3306/jmpower";
String user="root";
String password="021107";
conn= DriverManager.getConnection(url,user,password);
String sql="";
if(pcode==null){//省份
sql="select code,name from t_area where pcode is null";
ps=conn.prepareStatement(sql);
rs=ps.executeQuery();
}else{//市区
sql="select code,name from t_area where pcode=?";
ps=conn.prepareStatement(sql);
ps.setString(1,pcode);
rs=ps.executeQuery();
}
while(rs.next()){
String code=rs.getString("code");
String name=rs.getString("name");
Area a=new Area(code,name);
areaList.add(a);
}
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
//使用fastjson将java对象转换成json字符串
String json = JSON.toJSONString(areaList);
//响应json
out.print(json);
}
}
区分同源和不同源的三要素
协议一致,域名一致,端口号一致,三个要素都一致,才是同源,其它一律都是不同源
URL1 | URL2 | 是否同源 | 描述 |
---|---|---|---|
http://localhost:8080/a/index.html | http://localhost:8080/a/first | 同源 | 协议 域名 端口一致 |
http://localhost:8080/a/index.html | http://localhost:8080/b/first | 同源 | 协议 域名 端口一致 |
http://www.myweb.com:8080/a.js | https://www.myweb.com:8080/b.js | 不同源 | 协议不同 |
http://www.myweb.com:8080/a.js | http://www.myweb.com:8081/b.js | 不同源 | 端口不同 |
http://www.myweb.com/a.js | http://www.myweb2.com/b.js | 不同源 | 域名不同 |
http://www.myweb.com/a.js | http://crm.myweb.com/b.js | 不同源 | 子域名不同 |
核心原理:跨域访问的资源允许你跨域访问。
实现:
//被访问资源设置响应头
response.setHeader("Access-Control-Allow-Origin", "http://localhost:8080"); // 允许某个
response.setHeader("Access-Control-Allow-Origin", "*"); // 允许所有
直接将访问地址写入script标签中(服务开启后即起效)
<script type="text/javascript" src="http://localhost:8081/b/jsonp1?fun=sum">script>
在script标签内部,编写生成用来访问的script标签(触发事件后起效)
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jsonp跨域,达到局部刷新的效果title>
head>
<body>
<script type="text/javascript">
function sayHello(data){
document.getElementById("div").innerHTML=data.name
}
window.onload=()=>{
document.getElementById("btn").onclick=()=>{
//创建script元素对象
var htmlScriptElement = document.createElement("script");
//设置script的type属性
htmlScriptElement.type="text/javascript"
//设置script的src属性
htmlScriptElement.src="http://localhost:8081/b/jsonp2?fun=sayHello"
//将script对象添加到body标签中(这一步就是加载script)
document.getElementsByTagName("body")[0].appendChild(htmlScriptElement)
}
}
script>
<button id="btn">jsonp解决跨域问题,达到ajax局部刷新的效果button>
<div id="div">div>
body>
html>
牛人们写的jQuery库,已经对jsonp进行了封装。大家可以直接拿来用。
用之前需要引入jQuery库的js文件。(这里的jQuery库咱们就不再封装了,咱们直接用jQuery写好的jsonp方式。)
jQuery中的jsonp其实就是我们方案2的高度封装,底层原理完全相同。
核心代码
$.ajax({
type : "GET",
url : "跨域的url",
dataType : "jsonp", // 指定数据类型
jsonp : "fun", // 指定参数名(不设置的时候,默认是:"callback")
jsonpCallback : "sayHello" // 指定回调函数的名字
// (不设置的时候,jQuery会自动生成一个随机的回调函数,
//并且这个回调函数还会自动调用success的回调函数。)
})
使用httpclient组件的方式
HttpClientSendGet(直接cv,无需记忆):
package com.bjpowernode.httpclient;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class HttpClientSendGet {
public static void main(String[] args) throws Exception {
// 使用java代码去发送HTTP get请求
// 目标地址
//String url = "https://www.baidu.com";
String url = "http://localhost:8081/b/hello";
HttpGet httpGet = new HttpGet(url);
// 设置类型 "application/x-www-form-urlencoded" "application/json"
httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
//System.out.println("调用URL: " + httpGet.getURI());
// httpClient实例化
CloseableHttpClient httpClient = HttpClients.createDefault();
// 执行请求并获取返回
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
//System.out.println("返回状态码:" + response.getStatusLine());
// 显示结果
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
String line = null;
StringBuffer responseSB = new StringBuffer();
while ((line = reader.readLine()) != null) {
responseSB.append(line);
}
System.out.println("服务器响应的数据:" + responseSB);
reader.close();
httpClient.close();
}
}
ajax5.html:发送ajax请求:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>使用代理机制完成ajax跨域访问</title>
</head>
<body>
<script type="text/javascript" src="/a/js/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
$(function (){
$("#btn").click(function (){
$.ajax({
type:"GET",
url:"http://localhost:8080/a/proxy",
async:true,
success:function (data){
$("#div").html(data)
}
})
})
})
</script>
<button id="btn">使用代理机制完成ajax跨域访问</button>
<div id="div"></div>
</body>
</html>
ProxyServlet:发送get请求,访问b站点TargerServlet,请求响应回来数据在进行响应
package com.jmpower.a.web.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 org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
//代理程序(中间商)
@WebServlet("/proxy")
public class ProxyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 通过httpclient组件,发送HTTP GET请求,访问 TargetServlet
String url = "http://localhost:8081/b/target";
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpResponse res = httpClient.execute(httpGet);
HttpEntity entity = res.getEntity();
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
String line = null;
StringBuffer responseSB = new StringBuffer();
while ((line = reader.readLine()) != null) {
responseSB.append(line);
}
System.out.println("服务器响应的数据:" + responseSB);
reader.close();
httpClient.close();
//responseSB为b站点响应回来的数据,再将此数据响应到前端页面
response.getWriter().print(responseSB);
}
}
TargetServlet:
package com.jmpower.b.web.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;
@WebServlet("/target")
public class TargetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//响应一个json字符串
response.getWriter().print("{\"username\":\"jackson\"}");
}
}
代码实现
前端:向后端发送请求,接收后端响应数据,绘制页面
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax实现搜索联想和自动补全功能title>
<style>
.userInput{
width: 300px;
height: 25px;
font-size: 20px;
padding-left: 5px;
}
.showDataDiv{
width: 310px;
border: 1px solid lightgray;
background-color: yellow;
display: none;
}
.showDataDiv p{
padding-left: 5px;
margin-top: 2px;
margin-bottom: 2px;
}
.showDataDiv p:hover{
cursor: pointer;
border: 1px solid blue;
background-color: tomato;
}
style>
head>
<body>
<script type="text/javascript">
//使用原生的ajax实现搜索联想和自动补全
window.onload=()=>{
document.getElementById("keywords").onkeyup=function(){//需要this,用function
if(this.value==""){
document.getElementById("datadiv").style.display="none";
}else{
//每当键盘弹起就发送ajax请求,实现联想
//1.创建核心对象
var xhr = new XMLHttpRequest();
//2.注册回调函数
xhr.onreadystatechange=()=>{
if(xhr.readyState==4){
if(xhr.status>=200&&xhr.status<300){
//[{"content":"javaweb"},{"content":"javascript"},{"content":"java"}]
var json = JSON.parse(xhr.responseText);//将后端响应的json字符串转换为json对象
html=""
for(let i=0;i<json.length;i++){
html+="+json[i].content+"\")'>"+json[i].content+"
"
}
document.getElementById("datadiv").innerHTML=html
document.getElementById("datadiv").style.display="block"
}
}
}
//3.开启通道
xhr.open("GET","/ajax_autocomplete/query?_="+new Date().getTime()+"&keywords="+this.value,true)
//4.发送请求
xhr.send()
}
}
}
function setInput(content){
document.getElementById("keywords").value=content;
document.getElementById("datadiv").style.display="none";
}
script>
<input type="text" class="userInput" id="keywords">
<div class="showDataDiv" id="datadiv">
div>
body>
html>
后端:查询数据,响应json格式字符串数据给前端
package com.jmpower.ajax.servletr;
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.sql.*;
@WebServlet("/query")
public class QueryServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取前端请求的参数
String keywords = request.getParameter("keywords");
//创建Json字符串
StringBuilder sb=new StringBuilder();
sb.append("[");
//连接数据库,进行查询
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/jmpower","root","021107");
String sql="select content from t_ajax where content like ?";
ps=conn.prepareStatement(sql);
ps.setString(1,keywords+"%");
rs=ps.executeQuery();
while(rs.next()){
String content = rs.getString("content");
sb.append("{\"content\":\""+content+"\"},");
}
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
String s="";
if(sb.length()>1){
s = sb.substring(0, sb.length() - 1);
}
s+="]";
//响应json格式的字符串给前端
response.getWriter().print(s);
}
}
消息: | 描述: |
---|---|
100 Continue | 服务器仅接收到部分请求,但是一旦服务器并没有拒绝该请求,客户端应该继续发送其余的请求。 |
101 Switching Protocols | 服务器转换协议:服务器将遵从客户的请求转换到另外一种协议。 |
消息: | 描述: |
---|---|
200 OK | 请求成功(其后是对GET和POST请求的应答文档。) |
201 Created | 请求被创建完成,同时新的资源被创建。 |
202 Accepted | 供处理的请求已被接受,但是处理未完成。 |
203 Non-authoritative Information | 文档已经正常地返回,但一些应答头可能不正确,因为使用的是文档的拷贝。 |
204 No Content | 没有新文档。浏览器应该继续显示原来的文档。如果用户定期地刷新页面,而Servlet可以确定用户文档足够新,这个状态代码是很有用的。 |
205 Reset Content | 没有新文档。但浏览器应该重置它所显示的内容。用来强制浏览器清除表单输入内容。 |
206 Partial Content | 客户发送了一个带有Range头的GET请求,服务器完成了它。 |
消息: | 描述: |
---|---|
300 Multiple Choices | 多重选择。链接列表。用户可以选择某链接到达目的地。最多允许五个地址。 |
301 Moved Permanently | 所请求的页面已经转移至新的url。 |
302 Found | 所请求的页面已经临时转移至新的url。 |
303 See Other | 所请求的页面可在别的url下被找到。 |
304 Not Modified | 未按预期修改文档。客户端有缓冲的文档并发出了一个条件性的请求(一般是提供If-Modified-Since头表示客户只想比指定日期更新的文档)。服务器告诉客户,原来缓冲的文档还可以继续使用。 |
305 Use Proxy | 客户请求的文档应该通过Location头所指明的代理服务器提取。 |
306 Unused | 此代码被用于前一版本。目前已不再使用,但是代码依然被保留。 |
307 Temporary Redirect | 被请求的页面已经临时移至新的url。 |
消息: | 描述: |
---|---|
400 Bad Request | 服务器未能理解请求。 |
401 Unauthorized | 被请求的页面需要用户名和密码。 |
402 Payment Required | 此代码尚无法使用。 |
403 Forbidden | 对被请求页面的访问被禁止。 |
404 Not Found | 服务器无法找到被请求的页面。 |
405 Method Not Allowed | 请求中指定的方法不被允许。 |
406 Not Acceptable | 服务器生成的响应无法被客户端所接受。 |
407 Proxy Authentication Required | 用户必须首先使用代理服务器进行验证,这样请求才会被处理。 |
408 Request Timeout | 请求超出了服务器的等待时间。 |
409 Conflict | 由于冲突,请求无法被完成。 |
410 Gone | 被请求的页面不可用。 |
411 Length Required | “Content-Length” 未被定义。如果无此内容,服务器不会接受请求。 |
412 Precondition Failed | 请求中的前提条件被服务器评估为失败。 |
413 Request Entity Too Large | 由于所请求的实体的太大,服务器不会接受请求。 |
414 Request-url Too Long | 由于url太长,服务器不会接受请求。当post请求被转换为带有很长的查询信息的get请求时,就会发生这种情况。 |
415 Unsupported Media Type | 由于媒介类型不被支持,服务器不会接受请求。 |
416 | 服务器不能满足客户在请求中指定的Range头。 |
417 Expectation Failed |
消息: | 描述: |
---|---|
500 Internal Server Error | 请求未完成。服务器遇到不可预知的情况。 |
501 Not Implemented | 请求未完成。服务器不支持所请求的功能。 |
502 Bad Gateway | 请求未完成。服务器从上游服务器收到一个无效的响应。 |
503 Service Unavailable | 请求未完成。服务器临时过载或当机。 |
504 Gateway Timeout | 网关超时。 |
505 HTTP Version Not Supported | 服务器不支持请求中指明的HTTP协议版本。 |
感谢动力节点杜老师:https://www.bilibili.com/video/BV1cR4y1P7B1/?spm_id_from=333.999.0.0