Java Web 从入门到退坑 —— 第十五章 AJAX 请求
By: -gregPerlinLi-
1. 什么是 AJAX 请求
AJAX 即 Asynchronous JavaScript And XML
(异步 JavaScript 和 XML),是指一种创建交互式网页应用的网页开发技术。
AJAX 是一种浏览器通过 JavaScript 异步发起请求,局部更新页面的技术。
局部更新:浏览器地址栏不会发生变化,而且局部更新不会舍弃原来页面的内容。
异步请求:在执行请求的时候后面的代码会继续执行,不会等待返回请求结果。
2. 原生 AJAX 请求的示例
HTML 页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AJAX</title>
<style type="text/css">
body {
font-family: Futura, "PingFang SC", Helvetica, Arial, sans-serif;
}
</style>
<script type="text/javascript">
/**
* Use JavaScript language to initiate AJAX request and access javaScriptAjax() method in server AjaxServlet class
*/
function ajaxRequest() {
// 1. Create XMLHttpRequest.
var xmlHttpRequest = new XMLHttpRequest();
// 2. Call the open method to set the request parameters.
xmlHttpRequest.open("GET", "http://localhost:8080/JsonAjaxI18n/ajaxServlet?action=javaScriptAjax", true);
// 3. Bind the onreadystatechange time before the send method to process the operation after the request is completed.
xmlHttpRequest.onreadystatechange = function () {
if ( xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200 ) {
var jsonObj = JSON.parse(xmlHttpRequest.responseText);
// Display the response data on the page
document.getElementById("div01").innerHTML = "No: " + jsonObj.id + "<br/>" + "Name: " + jsonObj.name ;
}
}
// 4. Call the send method to send the request.
xmlHttpRequest.send();
}
</script>
</head>
<body>
<button onclick="ajaxRequest()">AJAX Request</button>
<div id="div01"></div>
</body>
</html>
BaseServlet.java
package com.gregperlinli.servlet;
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.lang.reflect.Method;
/**
* @author gregperlinli
*/
@WebServlet(name = "BaseServlet", value = "/BaseServlet")
public abstract class BaseServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Solve the problem of Chinese garbled code in POST request
request.setCharacterEncoding("UTF-8");
// Solve the response Chinese garbled
response.setContentType("text/html; charset=UTF-8");
String action = request.getParameter("action");
try {
// Through the action business identification string, get the corresponding business method reflection
Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
// Call target business method
method.invoke(this, request, response);
} catch ( Exception e ) {
e.printStackTrace();
}
}
}
AjaxServlet.java
package com.gregperlinli.servlet;
import com.google.gson.Gson;
import com.gregperlinli.pojo.Person;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author gregperlinli
*/
@WebServlet(name = "AjaxServlet", value = "/ajaxServlet")
public class AjaxServlet extends BaseServlet {
protected void javaScriptAjax(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("The AJAX request is arrive!");
Person person = new Person(1, "XiaoMing");
// String in JSON format
Gson gson = new Gson();
String personJsonString = gson.toJson(person);
response.getWriter().write(personJsonString);
}
}
3. jQuery 中的 AJAX 请求
$.ajax
方法
url
表示请求的地址
type
表示请求的类型 GET
或 POST
请求
data
表示发送给服务器的数据
格式有两种:1. name = value & name = value
2. { key : value }
success
请求成功,响应的回调函数(回调函数一定要带一个参数以接收服务器传来的数据)
dataType
响应的数据类型
常用的数据类型有:text
表示纯文本
xml
表示 XML 数据
json
表示 JSON 对象
示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Ajax Request</title>
<style type="text/css">
body {
font-family: Futura, "PingFang SC", Helvetica, Arial, sans-serif;
}
</style>
<script type="text/javascript" src="script/jQuery.js"></script>
<script type="text/javascript">
$(function () {
// Ajax Request
$("#ajaxBtn").click(function () {
$.ajax({
url: "http://localhost:8080/JsonAjaxI18n/ajaxServlet",
// data: "action=jQueryAjax",
data: {action: "jQueryAjax"},
type: "GET",
success: function ( data ) {
alert("The data returned by the server is: " + data);
// var jsonObj = JSON.parse(data);
$("#msg").html("No.: " + data.id + "<br/>Name: " + data.name);
},
dataType: "json"
});
});
});
</script>
</head>
<body>
<div>
<button id="ajaxBtn">$.ajax Request</button>
<button id="getBtn">$.get Request</button>
<button id="postBtn">$.post Request</button>
<button id="getJSONBtn">$.getJSON Request</button>
</div>
<div id="msg"></div>
<br>
<br/>
<form>
<label>
Username: <input type="text" name="username" /><br/>
Password: <input type="password" name="password" /><br/>
Drop down radio select:
<select name="single">
<option value="single1">Single 1</option>
<option value="single2">Single 2</option>
<option value="single3">Single 3</option>
</select><br/>
Drop down multiple select:
<select name="multiple" multiple="multiple">
<option value="multiple1">Multiple 1</option>
<option value="multiple2">Multiple 2</option>
<option value="multiple3">Multiple 3</option>
</select>
<br/>
Check box: <input type="checkbox" name="checkbox">check1<input type="checkbox" name="checkbox">check2<br/>
Radio box: <input type="radio" name="radio">radio1<input type="radio" name="radio">radio2<br/>
<input type="submit" id="submit" value="Submit--serialize()">
</label>
</form>
</body>
</html>
AjaxServlet.java
package com.gregperlinli.servlet;
import com.google.gson.Gson;
import com.gregperlinli.pojo.Person;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author gregperlinli
*/
@WebServlet(name = "AjaxServlet", value = "/ajaxServlet")
public class AjaxServlet extends BaseServlet {
protected void jQueryAjax(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("The jQuery AJAX request is arrive!");
Person person = new Person(1, "XiaoMing");
// String in JSON format
Gson gson = new Gson();
String personJsonString = gson.toJson(person);
response.getWriter().write(personJsonString);
}
}
$.get
方法和 $.post
方法
通过 HTTP GET/POST 请求从服务器上请求数据
url
请求的 URL 地址
data
发送的数据
callback
成功的回调函数
type
返回的数据类型
示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Ajax Request</title>
<style type="text/css">
body {
font-family: Futura, "PingFang SC", Helvetica, Arial, sans-serif;
}
</style>
<script type="text/javascript" src="script/jQuery.js"></script>
<script type="text/javascript">
$(function () {
// Ajax--get Request
$("#getBtn").click(function () {
$.get("http://localhost:8080/JsonAjaxI18n/ajaxServlet",
"action=jQueryGet",
function ( data ) {
$("#msg").html("No.: " + data.id + "<br/>Name: " + data.name);
},
"json"
);
});
// Ajax--post Request
$("#postBtn").click(function () {
$.get("http://localhost:8080/JsonAjaxI18n/ajaxServlet",
"action=jQueryPost",
function ( data ) {
$("#msg").html("No.: " + data.id + "<br/>Name: " + data.name);
},
"json"
);
});
});
</script>
</head>
<body>
<div>
<button id="ajaxBtn">$.ajax Request</button>
<button id="getBtn">$.get Request</button>
<button id="postBtn">$.post Request</button>
<button id="getJSONBtn">$.getJSON Request</button>
</div>
<div id="msg"></div>
<br>
<br/>
<form>
<label>
Username: <input type="text" name="username" /><br/>
Password: <input type="password" name="password" /><br/>
Drop down radio select:
<select name="single">
<option value="single1">Single 1</option>
<option value="single2">Single 2</option>
<option value="single3">Single 3</option>
</select><br/>
Drop down multiple select:
<select name="multiple" multiple="multiple">
<option value="multiple1">Multiple 1</option>
<option value="multiple2">Multiple 2</option>
<option value="multiple3">Multiple 3</option>
</select>
<br/>
Check box: <input type="checkbox" name="checkbox">check1<input type="checkbox" name="checkbox">check2<br/>
Radio box: <input type="radio" name="radio">radio1<input type="radio" name="radio">radio2<br/>
<input type="submit" id="submit" value="Submit--serialize()">
</label>
</form>
</body>
</html>
AjaxServlet.java
package com.gregperlinli.servlet;
import com.google.gson.Gson;
import com.gregperlinli.pojo.Person;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author gregperlinli
*/
@WebServlet(name = "AjaxServlet", value = "/ajaxServlet")
public class AjaxServlet extends BaseServlet {
protected void jQueryGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("The jQuery GET request is arrive!");
Person person = new Person(1, "XiaoMing");
// String in JSON format
Gson gson = new Gson();
String personJsonString = gson.toJson(person);
response.getWriter().write(personJsonString);
}
protected void jQueryPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("The jQuery POST request is arrive!");
Person person = new Person(1, "XiaoMing");
// String in JSON format
Gson gson = new Gson();
String personJsonString = gson.toJson(person);
response.getWriter().write(personJsonString);
}
}
$.getJSON
方法
通过 HTTP GET 请求从服务器上请求 JSON 数据
url
请求的 URL 地址
data
发送的数据
callback
成功的回调函数
示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Ajax Request</title>
<style type="text/css">
body {
font-family: Futura, "PingFang SC", Helvetica, Arial, sans-serif;
}
</style>
<script type="text/javascript" src="script/jQuery.js"></script>
<script type="text/javascript">
$(function () {
// Ajax--getJson Request
$("#getJSONBtn").click(function () {
$.getJSON("http://localhost:8080/JsonAjaxI18n/ajaxServlet",
"action=jQueryGetJson",
function ( data ) {
$("#msg").html("No.: " + data.id + "<br/>Name: " + data.name);
}
);
});
});
</script>
</head>
<body>
<div>
<button id="ajaxBtn">$.ajax Request</button>
<button id="getBtn">$.get Request</button>
<button id="postBtn">$.post Request</button>
<button id="getJSONBtn">$.getJSON Request</button>
</div>
<div id="msg"></div>
<br>
<br/>
<form>
<label>
Username: <input type="text" name="username" /><br/>
Password: <input type="password" name="password" /><br/>
Drop down radio select:
<select name="single">
<option value="single1">Single 1</option>
<option value="single2">Single 2</option>
<option value="single3">Single 3</option>
</select><br/>
Drop down multiple select:
<select name="multiple" multiple="multiple">
<option value="multiple1">Multiple 1</option>
<option value="multiple2">Multiple 2</option>
<option value="multiple3">Multiple 3</option>
</select>
<br/>
Check box: <input type="checkbox" name="checkbox">check1<input type="checkbox" name="checkbox">check2<br/>
Radio box: <input type="radio" name="radio">radio1<input type="radio" name="radio">radio2<br/>
<input type="submit" id="submit" value="Submit--serialize()">
</label>
</form>
</body>
</html>
AjaxServlet.java
package com.gregperlinli.servlet;
import com.google.gson.Gson;
import com.gregperlinli.pojo.Person;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author gregperlinli
*/
@WebServlet(name = "AjaxServlet", value = "/ajaxServlet")
public class AjaxServlet extends BaseServlet {
protected void jQueryGetJson(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("The jQuery GetJSON request is arrive!");
Person person = new Person(1, "XiaoMing");
// String in JSON format
Gson gson = new Gson();
String personJsonString = gson.toJson(person);
response.getWriter().write(personJsonString);
}
}
serialize()
表单序列化方法
把表单中所有表单项的内容获取到并以 name = value & name = value
的形式进行拼接。
示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Ajax Request</title>
<style type="text/css">
body {
font-family: Futura, "PingFang SC", Helvetica, Arial, sans-serif;
}
</style>
<script type="text/javascript" src="script/jQuery.js"></script>
<script type="text/javascript">
$(function () {
// Ajax Request
$("#submit").click(function () {
// Parameter serialization
alert($("#form01").serialize());
$.getJSON("http://localhost:8080/JsonAjaxI18n/ajaxServlet",
"action=jQuerySerialize&" + $("#form01").serialize(),
function ( data) {
$("#msg").html("Serialize:<br/>No.: " + data.id + "<br/>Name: " + data.name);
});
})
});
</script>
</head>
<body>
<div>
<button id="ajaxBtn">$.ajax Request</button>
<button id="getBtn">$.get Request</button>
<button id="postBtn">$.post Request</button>
<button id="getJSONBtn">$.getJSON Request</button>
</div>
<div id="msg"></div>
<br>
<br/>
<form id="form01">
<label>
Username: <input type="text" name="username" /><br/>
Password: <input type="password" name="password" /><br/>
Drop down radio select:
<select name="single">
<option value="single1">Single 1</option>
<option value="single2">Single 2</option>
<option value="single3">Single 3</option>
</select><br/>
Drop down multiple select:
<select name="multiple" multiple="multiple">
<option value="multiple1">Multiple 1</option>
<option value="multiple2">Multiple 2</option>
<option value="multiple3">Multiple 3</option>
</select>
<br/>
Check box: <input type="checkbox" name="checkbox">check1<input type="checkbox" name="checkbox">check2<br/>
Radio box: <input type="radio" name="radio">radio1<input type="radio" name="radio">radio2<br/>
<input type="submit" id="submit" value="Submit--serialize()">
</label>
</form>
</body>
</html>
AjaxServlet.java
package com.gregperlinli.servlet;
import com.google.gson.Gson;
import com.gregperlinli.pojo.Person;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author gregperlinli
*/
@WebServlet(name = "AjaxServlet", value = "/ajaxServlet")
public class AjaxServlet extends BaseServlet {
protected void jQuerySerialize(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("The jQuery Serialize request is arrive!");
System.out.println("Username: " + request.getParameter("username"));
System.out.println("Password: " + request.getParameter("password"));
Person person = new Person(1, "XiaoMing");
// String in JSON format
Gson gson = new Gson();
String personJsonString = gson.toJson(person);
response.getWriter().write(personJsonString);
}
}