利用fastjson解析json并通過js&ajax實(shí)現(xiàn)頁面的無跳轉(zhuǎn)刷新
1.json是一種優(yōu)秀的數(shù)據(jù)格式,在移動(dòng)開發(fā)和web開發(fā)中經(jīng)常用到,本例中通過一個(gè)小案例講解如何通過alibaba的開源框架fastjson來解析jason數(shù)據(jù)格式并通過js實(shí)現(xiàn)無跳轉(zhuǎn)刷新
2,新建一個(gè)web項(xiàng)目,這是我的項(xiàng)目:我這里直接用servlet寫的

注意導(dǎo)包,我這里到了很多無用的包,其實(shí)主要的包是下面幾個(gè):

這個(gè)三個(gè)包是必須的,其他都是開發(fā)基本web的常用包
3.創(chuàng)建一個(gè)domain:
package com.keson.domain;
import com.thoughtworks.xstream.annotations.XStreamAlias;
@XStreamAlias("employee")
public class Employee {
@XStreamAlias("no")
private Integer no;
@XStreamAlias("name")
private String name;
@XStreamAlias("age")
private Integer age;
@XStreamAlias("gender")
private String gender;
@XStreamAlias("job")
private String job;
public Integer getNo() {
return no;
}
public void setNo(Integer no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
}
注意:這里的domain必須用@XStreamAlias("employee")注解,以便把domain轉(zhuǎn)成json數(shù)據(jù)格式,屬性名字最好和注解里面的標(biāo)識(shí)名字一樣
3,.這是一個(gè)servlet:
public class JsonServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Employee employee =new Employee();
employee=getEmployee();
XStream xStream = new XStream(new DomDriver());
xStream.autodetectAnnotations(true);
response.setHeader("Cache-Control", "no-cache");
response.setContentType("text/json; charset=utf-8");
PrintWriter writer = response.getWriter();
String jsonResult = JSON.toJSONString(employee, false);
System.out.println(jsonResult);
writer.write(jsonResult);
writer.close();
}
public static Employee getEmployee(){
Employee employee=new Employee();
employee.setNo(1);
employee.setName("keson");
employee.setAge(20);
employee.setGender("M");
employee.setJob("軟件工程師");
return employee;
}
}
這里的數(shù)據(jù)我是通過偽造的,當(dāng)然如果有數(shù)據(jù)庫的話可以通過jdbc或其他持久層框架來實(shí)現(xiàn),這里只是舉例,所以數(shù)據(jù)偽造簡(jiǎn)便些
標(biāo)紅色的部分是怎樣通過java代碼把對(duì)象轉(zhuǎn)成json數(shù)據(jù)的,這個(gè)基本上是可以套用的
4.jsp頁面:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<script type="text/javascript">
var root_path = "${pageContext.request.contextPath}";
</script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/show.js"></script>
</head>
<body>
<table border="1px">
<tr>
<td>no</td>
<td>name</td>
<td>age</td>
<td>gender</td>
<td>job</td>
</tr>
<tr>
<td><input type="text" id="no_id"></td>
<td><input type="text" id="name_id"></td>
<td><input type="text" id="age_id"></td>
<td><input type="text" id="gender_id"></td>
<td><input type="text" id="job_id"></td>
</tr>
<tr><td colspan="5"><input type="button" value="提交" onclick="submitBtn()"></td></tr>
</table>
</body>
</html>
這里的jsp頁面非常簡(jiǎn)單也很簡(jiǎn)潔,我是通過js去實(shí)現(xiàn)數(shù)據(jù)交互的,所以在jsp頁面中沒有寫任何js的代碼
5.js代碼:
function submitBtn() {
reqeustDetail();
}
function createXMLHttpRequest() {
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
xmlHttp = null;
window.alert("Cannot support XMLHttpRequest");
}
return xmlHttp;
}
function reqeustDetail() {
var xmlHttp = createXMLHttpRequest();
var url =root_path+"/json";
if (xmlHttp) {
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState === 4) {
if (xmlHttp.status === 200) {
parseMessage(xmlHttp);
} else {
window.alert("Error number: " + xmlHttp.status
+ ", error describe: " + xmlHttp.statusText);
}
}
};
xmlHttp.send(null);
}
}
function parseMessage(xmlHttp) {
var jsondoc = xmlHttp.response;
// var obj = eval('('+jsondoc+')');
var obj=Function("return"+jsondoc)();
var no_id=document.getElementById("no_id");
var name_id=document.getElementById("name_id");
var age_id=document.getElementById("age_id");
var gender_id=document.getElementById("gender_id");
var job_id=document.getElementById("job_id");
no_id.value=obj.no;
name_id.value=obj.name;
age_id.value=obj.age;
gender_id.value=obj.gender;
job_id.value=obj.job;
}
這里是通過ajax實(shí)現(xiàn)異步請(qǐng)求,通過js的document.getElementById來獲取及賦值的,其實(shí)ajax部分基本上是套用,標(biāo)有顏色的部分才是去實(shí)現(xiàn)邏輯的,標(biāo)黃色部分是怎樣通過js去解析json的,非常的簡(jiǎn)便
6,測(cè)試
這是原始的頁面效果:

當(dāng)點(diǎn)擊提交時(shí)頁面會(huì)無跳轉(zhuǎn)刷新,可以觀察到URL沒有什么變化,最后的結(jié)果就是把數(shù)據(jù)帶過來了,而且響應(yīng)是非常快的,在數(shù)據(jù)量大的情況下效果可能更加明顯,結(jié)果如下圖:


浙公網(wǎng)安備 33010602011771號(hào)