利用fastjson解析json並通過js&ajax實現頁面的無跳轉重新整理

來源:互聯網
上載者:User

標籤:

1.json是一種優秀的資料格式,在移動開發和web開發中經常用到,本例中通過一個小案例講解如何通過alibaba的開源架構fastjson來解析jason資料格式並通過js實現無跳轉重新整理

2,建立一個web項目,這是我的項目:我這裡直接用servlet寫的

注意導包,我這裡到了很多無用的包,其實主要的包是下面幾個:

這個三個包是必須的,其他都是開發基本web的常用包

3.建立一個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轉成json資料格式,屬性名稱字最好和註解裡面的標識名字一樣

3,.這是一個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;
}
}

這裡的資料我是通過偽造的,當然如果有資料庫的話可以通過jdbc或其他持久層架構來實現,這裡只是舉例,所以資料偽造簡便些

標紅色的部分是怎樣通過java代碼把對象轉成json資料的,這個基本上是可以套用的

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頁面非常簡單也很簡潔,我是通過js去實現資料互動的,所以在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實現非同步請求,通過js的document.getElementById來擷取及賦值的,其實ajax部分基本上是套用,標有顏色的部分才是去實現邏輯的,標黃色部分是怎樣通過js去解析json的,非常的簡便

6,測試

這是原始的頁面效果:

當點擊提交時頁面會無跳轉重新整理,可以觀察到URL沒有什麼變化,最後的結果就是把資料帶過來了,而且響應是非常快的,在資料量大的情況下效果可能更加明顯,結果如:

 

利用fastjson解析json並通過js&ajax實現頁面的無跳轉重新整理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.