一、js代码
<script type="text/javascript" src="../js/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submitBn').click(function() {
var title = $('#title').val();
var now = new Date();
//alert(title);
var time = now.toLocaleString();
//alert(time);
var content = $('#content').val();
//alert(content);
if (title == null|| content == null|| time == null)
alert('输入错误,不能为空');
else {
$.ajax({
type : "post",
url : "fItemsAdd",//action的名字
dataType : "json",//数据类型为json
data : {
"title" : title,//将前台接收到的数据传给后台,因此action域中需要有相应的set方法
"content" : content,
"time" : time//避免麻烦,time都用字符串啦
},
success : function(data) {
<span style="white-space:pre"> </span>alert(data);//显示[objection objection],收到的data的类型。data.result为数据内容
<span style="white-space:pre"> </span>var result=JSON.parse(data.result);//将数据转换成result数组。可以通过result[0].title访问title内容
<span style="white-space:pre"> </span>alert(result);
<span style="white-space:pre"> </span>alert("data.result:"+data.result);//值
<span style="white-space:pre"> </span>window.location.href = "forum.jsp";
</script>
</pre><pre name="code" class="javascript">
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted
二、struts配置:
<action name="fItemsAdd" class="com.gslabs.action.FItemsAction" method="AddItems">
<result type="json">
<param name="root">responseJson</param>
</result>
</action>
public String AddItems(){
Gson gson = new Gson();
FItems fitem = new FItems();
fitem.setTitle(title);
fitem.setTime(time);;
fitem.setContent(content);
fItemsManager.AddItems(fitem);
System.out.println("this is in the AddItems Action for fitem "+fitem.getTitle());
responseJson=new HashMap<String, Object>();//respnseJson就是一个Map对象,标记result,也就是传回去的data
responseJson.put("result", gson.toJson(fitem));
return SUCCESS;
}