前两天在处理一个应用系统中提交表单问题的时候,遇到了表单数据需要较复杂的处理,不能直接提交的情况,处理后的内容比较多,不能直接使用get的方式串到URL的后面,于是想到了json,但json使用的并不熟练,在网上扒拉比较完整的介绍,很可惜,没有找到,后来查了些资料,实现了。简单的Demo如下:
Js文件:
$(function(){
//提交时的操作
$("#stuGoodsSubmit").click(function(){
$.ajax({
url:"/goods/ajax/goodsgrant.do",
data: {
"stuName": "测试twd",
"stuId":"1",
"goodsTypes": "1,2,3,4"
},
dateType:"json",
success:function(data) {
switch(data._rc){
case "success":
alert("操作成功!");
break;
case "input":
alert(data.message)
break;
default:
alert("操作失败!");
break;
}
}
})
})
})
Jsp文件:
<html>
<head>
<link href="<ww:url value='/common/css/main.css' server='file.ems' includeParams='none'/>" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<ww:url value='/common/js/jquery/jquery-1.4.4.min.js' server='file.hi' includeParams="none"/>"></script>
<script type="text/javascript" src="/goods/js/goodsGrant.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>物品发放</title>
</head>
<body>
<%@include file="inc/tag.inc"%>
<form id="stuGoodsForm" method="post">
<p align="center">
<input name="stuGoodsSubmit" type="button" id="stuGoodsSubmit" class="btn_1" value="提交"/>
</p>
</form>
</body>
</html>
Java文件:
public class GoodsGrantAction extends BaseAction{
//input
private Integer stuId;
private String stuName;
private String goodsTypes;
//output
private String message; //输出提示信息
//service
private GoodsService goodsService;
public String execute(){
String flag = SUCCESS;
if(stuId==null){
message = "学生信息丢失";
flag = INPUT;
}
System.out.println(stuId+" "+stuName+" "+goodsTypes);
return flag;
}
public Integer getStuId() {
return stuId;
}
public void setStuId(Integer stuId) {
this.stuId = stuId;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public String getGoodsTypes() {
return goodsTypes;
}
public void setGoodsTypes(String goodsTypes) {
this.goodsTypes = goodsTypes;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void setGoodsService(GoodsService goodsService) {
this.goodsService = goodsService;
}
}
Xml配置文件:
<xwork>
<package name="goods/ajax" extends="ajax-default" namespace="/goods/ajax">
<action name="goodsgrant" class="goodsGrantAction">
<result name="success" type="json">
</result>
<result name="input" type="json">
<param name="jsonObjectProperty">message</param>
</result>
</action>
</package>
</xwork>
上面的例子中,json是使用键值对的方式传输数据的,在客户端js中将json需要传输的内容放到对应的名称后,在服务器端根据对应的名称获取需要的数据。