一个简单json数据提交实例
1.客户端编程:jsp页面
<%@ page language="java" contentType="text/html;
charset=UTF-8"
<!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>
</head>
<script type="text/javascript" src="js/jquery-1.4.2.js"></script>
<script type="text/javascript" src="js/json2.js"></script>
<body>
<form action="">
<table>
<tr>
<td>名字</td>
<td><input type="text" id="name" name="name"/></td>
</tr>
<tr>
<td>年龄</td>
<td><input type="text" id="age" name="age"/></td>
</tr>
<tr>
<td><input type="button" value="提交" onclick="commit();"/> </td>
</tr>
</table>
<table id="ulist" border="2">
</table>
</form>
</body>
<script type="text/javascript">
function commit(){
{type : "post",
data:{name: $ (‘#name‘).val(),
url : "testJson_testJson.action",
dataType : "JSON",
success : callback
}
);
}
function callback(data){
var json = JSON.parse(data);
alert("fdf");
var ulist = $("#ulist");
$.each(json, function(i,item){
ulist.append(
"<tr><td>"+item.name+"</td><td>"+item.age+"</td></tr>"
);
})
}
</script>
</html>
2.服务端编程:用到sturst2
public class Person {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
public class TestJsonAction {
private static final long serialVersionUID = -3571998877536556903L;
public String testJson() throws Exception {
Person p1 = new Person();
p1.setName("nn");
p1.setAge("11");
Person p2 = new Person();
p2.setName("gg");
p2.setAge("12");
Person p3 = new Person();
p3.setName("rr");
p3.setAge("24");
List<Person> ulist = new ArrayList<Person>();
ulist.add(p1);
ulist.add(p2);
ulist.add(p3);
String name =ServletActionContext.getRequest().getParameter("name");
String age = ServletActionContext.getRequest().getParameter("age");
Person p4 = new Person();
p4.setName(name);
p4.setAge(age);
ulist.add(p4);
JSONArray json = JSONArray.fromObject(ulist);
ServletActionContext.getResponse().getWriter().print(json);
return null;
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。