利用fastjson解析json并通过js&ajax实现页面的无跳转刷新
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实现页面的无跳转刷新的更多相关文章
- Java基础/利用fastjson反序列化json为对象和对象数组
利用fastjson反序列化json为对象和对象数组 利用 fastjosn 将 .json文件 反序列化为 java.class 和 java.util.List fastjson 是一个性能很好的 ...
- Spring Boot返回json数据及完美使用FastJson解析Json数据
Spring Boot返回json数据 视频地址:http://www.iqiyi.com/w_19rubxzsr5.html 博文参考:https://blog.csdn.net/linxingl ...
- fastjson解析json数组
1.fastjson解析json数组(直接上代码) import java.util.ArrayList; import java.util.List; import com.alibaba.fast ...
- FastJson解析Json,封装JavaBean对象
获取到前端的Json,后台对应封装JavaBean对象,对其解析赋值 获取到前端的json,对其进行分析 1.获取最外层前端json对应得JavaBean (1)未分析格式的json串 (2)初步格式 ...
- Scala中使用fastJson 解析json字符串
Scala中使用fastJson 解析json字符串 添加依赖 2.解析json字符 2.1可以通过JSON中的parseObject方法,把json字符转转换为一个JSONObject对象 2.2然 ...
- JS 模拟手机页面文件的下拉刷新
js 模拟手机页面文件的下拉刷新初探 老总说需要这个功能,好吧那就看看相关的东西呗 最后弄出了一个简单的下拉刷新页面的形式,还不算太复杂 查看 demo 要在仿真器下才能看到效果,比如chrome的里 ...
- 使用jQuery解析JSON数据(由ajax发送请求到php文件处理数据返回json数据,然后解析json写入html中呈现)
在上一篇的Struts2之ajax初析中,我们得到了comments对象的JSON数据,在本篇中,我们将使用jQuery进行数据解析. 我们先以解析上例中的comments对象的JSON数据为例,然后 ...
- FastJSON解析Json字符串(反序列化为List、Map)
在日常开发与数据库打交道的时候,常有以Json格式的字符串存储到数据库的情况,当在Java程序中获取到对应的Json格式的String字符串后,如何才能转换为我们想要的数据格式(比如转换成Java中的 ...
- 78. Spring Boot完美使用FastJson解析JSON数据【从零开始学Spring Boot】
[原创文章,转载请注明出处] 个人使用比较习惯的json框架是fastjson,所以spring boot默认的json使用起来就很陌生了,所以很自然我就想我能不能使用fastjson进行json解析 ...
随机推荐
- dl,dt,dd标签的使用
dl就是定义一个列表 dt说明白了就是这个列表的标题dd就是内容,能缩进和UL,OL性质差不多 <dl> <dt>标题标题</dt> <dd>内容内容& ...
- 洛谷P1220关路灯题解
题目 此题是一个状态转移方程还算比较多的一个区间DP,这个题也能启示我们如果某个状态不能够很好地解决问题,那么不妨试试再加一维,而且如果转移顺序不确定的话,可以试试记忆化搜索,说不定就可以比较容易的写 ...
- [M$]微软提供的ProcessExplorer等系统工具集合
https://docs.microsoft.com/en-us/sysinternals/downloads/index
- dajngo cache,throttling
缓存 背景介绍: 动态网站的问题就在于它是动态的. 也就是说每次用户访问一个页面,服务器要执行数据库查询,启动模板,执行业务逻辑以及最终生成一个你所看到的网页,这一切都是动态即时生成的. 从处理器资源 ...
- Linux-服务器创建swap交换分区
服务器 swap 交换分区制作 作用:‘提升‘ 内存的容量,防止OOM(Out Of Memory) 查看当前的交换分区 # cat /proc/swaps # free -m # swapon -s ...
- springboot2.0整合es的异常总结
异常: availableProcessors is already set to [4], rejecting [4] 在启动类中加入 System.setProperty("es.set ...
- openssl命令行将pfx格式转.key和.crt文件,Apache适用
以前使用的windows平台作为php运行的平台,感觉整体速度太慢,于是现在改为centos系统的linux平台.需要把windows中用pfx证书转为appache用到key和crt组成的证书 将* ...
- RTC子系统
目录 RTC子系统 引入 hctosys.c interface.c class.c 小结 流程一览 框架分析 rtc_init rtc_device_register s3c_rtc_probe o ...
- Python之False和None
这个其实在Python文档当中有写了,为了准确起见,我们先引用Python文档当中的原文: In the context of Boolean operations, and also when ex ...
- SpringBoot项目@RestController使用 redirect 重定向无效
Spring MVC项目中页面重定向一般使用return "redirect:/other/controller/";即可. 而Spring Boot当我们使用了@RestCont ...