ajax是什麼?
asynchronous javascript and xml(異步的javascript和xml),其實質可以理解 爲:
使用瀏覽器內置的一個對象(XmlHttpRequest)向服務器發送請求,
服務器返回xml數據或者是文本數據給瀏覽器,
然後在瀏覽器端,使用這些數據更新部分頁面,整個過程,頁面無任何的刷新。
這裏我們以上一篇中的登錄爲例,不採用表單提交方式,而是用ajax請求。
一,更改login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="./js/login.js"></script>
</head>
<body>
<label>用戶名</label>
<input type="text" id="name" name="name" />
<br/>
<label>密碼</label>
<input type="text" id="password" name="password" />
<br/><br/>
<button οnclick="login()">登錄</button>
<span id="msg"></span>
</body>
</html>
二,在webapp目錄下新建js/login.js
function login() {
var name = document.getElementById('name').value;
var password = document.getElementById('password').value;
// 獲取XmlHttpRequest對象
var xhr = getXmlHttpRequest();
xhr.open('post', '/webDemo/send_ajax', false);
// 必須添加一個消息頭content-type
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.onreadystatechange=function(){
//編寫相應的處理代碼
if(xhr.readyState == 4){
//只有readyState等亍4,xhr才完整地接收到了服務器返回的數據。
if (xhr.status == 200) {
//獲得文本數據
var txt = xhr.responseText;
//dom操作、更新頁面
document.getElementById('msg').innerHTML=txt;
} else {
document.getElementById('msg').innerHTML="系統錯誤";
}
}
};
xhr.send('name='+name+'&password='+password);
}
function getXmlHttpRequest() {
var xhr = null;
if ((typeof XMLHttpRequest) != 'undefined') {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHttp');
}
return xhr;
}
三,新建AjaxServlet
package com.example.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AjaxServlet extends HttpServlet {
private static final long serialVersionUID = 6364639862439643474L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
super.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//設置請求參數編碼
req.setCharacterEncoding("utf-8");
//設置響應格式
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
String name = req.getParameter("name");
String password = req.getParameter("password");
//獲取輸出流
PrintWriter out = resp.getWriter();
if (name.equals("李四") && password.equals("123")) {
out.println("登錄成功");
} else {
out.println("用戶名或密碼錯誤");
}
out.flush();
out.close();
}
}
四,在web.xml中配置映射
<servlet>
<servlet-name>AjaxServlet</servlet-name>
<servlet-class>com.example.servlet.AjaxServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AjaxServlet</servlet-name>
<url-pattern>/send_ajax</url-pattern>
</servlet-mapping>
五,啓動測試:http://localhost:8088/webDemo/login.html
返回結果:
可以看到,頁面沒有刷新,返回數據成功。
這裏返回的是text文本信息,那麼我們如何從後臺獲取到需要的數據顯示到頁面呢?
這裏我們就需要用到Json字符串格式來傳遞數據了。
六,引入jackson的依賴包:
<!-- jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.6.5</version>
</dependency>
七,在login.html中添加一個查詢按鈕:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="./js/login.js"></script>
</head>
<body>
<!-- 表單提交 -->
<!-- <form id="form" action="/webDemo/login.do" method="post">
<label>用戶名</label>
<input type="text" id="name" name="name" />
<br/>
<label>密碼</label>
<input type="text" id="password" name="password" />
<br/><br/>
<button οnclick="function(){document.getElementById('form').submit();}">登錄</button>
</form> -->
<!-- ajax請求 -->
<label>用戶名</label>
<input type="text" id="name" name="name" />
<br />
<label>密碼</label>
<input type="text" id="password" name="password" />
<br />
<br />
<button οnclick="login()">登錄</button>
<button οnclick="getAll()">查詢</button>
<span id="msg"></span>
<br />
<br />
<div id="div">
</div>
</body>
</html>
八,新增getAll()方法:
function getAll() {
// 獲取XmlHttpRequest對象
var xhr = getXmlHttpRequest();
xhr.open('get', '/webDemo/send_ajax', false);
//設置請求頭
xhr.setRequestHeader("Content-Type","application/json");
xhr.onreadystatechange=function(){
//編寫相應的處理代碼
if(xhr.readyState == 4){
//只有readyState等亍4,xhr才完整地接收到了服務器返回的數據。
if (xhr.status == 200) {
//獲得文本數據,json字符串格式
var txt = xhr.responseText;
//json轉換成js對象
var data = JSON.parse(txt);
//dom操作、表格顯示數據
var start = "<table width='600px' border='1' cellspacing='0' cellpadding='0'><thead><tr><td>用戶名</td><td>用戶密碼(已加密)</td></tr></thead><tbody>";
var end = "</tbody></table>";
var mid = "";
for (i in data) {
var userInfo = data[i];
var tbody = "<tr><td>"+userInfo.name+"</td><td>"+userInfo.password+"</td></tr>";
mid += tbody;
}
var table = start+mid+end;
document.getElementById('div').innerHTML=table;
} else {
document.getElementById('msg').innerHTML="系統錯誤";
}
}
};
xhr.send();
}
九,完善doGet請求:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//設置響應格式
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
UserInfo userInfo1 = new UserInfo();
userInfo1.setName("張三");
userInfo1.setPassword(MD5.getEncryption("123"));
UserInfo userInfo2 = new UserInfo();
userInfo2.setName("李四");
userInfo2.setPassword(MD5.getEncryption("456"));
List<UserInfo> list = new ArrayList<UserInfo>();
list.add(userInfo1);
list.add(userInfo2);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.INDENT_OUTPUT, Boolean.TRUE);
String json = mapper.writeValueAsString(list);
//獲取輸出流
PrintWriter out = resp.getWriter();
out.println(json);
out.flush();
out.close();
}
十,訪問測試:http://localhost:8088/webDemo/login.html
點擊查詢,返回結果:
1) 大家應該有注意到,servlet-mapping 這裏設置的是“/send_ajax”,
也就是說只有以“/send_ajax”結尾的請求才能訪問到AjaxServlet,根據post,get 請求自動匹配相應的doPost,doGet 方法
2) 前後端交互傳遞數據,這裏使用json字符串格式,
如果從前端需要傳遞參數到後臺,需要將js對象data轉換成json格式,JSON.stringify(data)
從後臺接收到的json格式數據也需要轉換成js對象才能使用,data = JSON.parse(xhr.responseText);
3) 上面說的是如何在js裏轉換json,在java代碼裏我們如何轉換呢?常用依賴包有jackson 和 fastjson,相關api 我們下篇再詳解。