您的位置:首页 > Web前端 > JQuery

Struts2+jQuery+Json零配置实现ajax

2014-09-20 21:40 369 查看
(一)Jsp页面代码

[b][c-sharp]
view plaincopy[/b]

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css">
-->
<mce:script type="text/javascript" src="js/jquery-1.6.1.js" mce_src="js/jquery-1.6.1.js"></mce:script>

<mce:script type="text/javascript"><!--
$(function(){

$("#str").click(function(){
$.ajax({
type: "post",
url: "http://localhost:8080/jsonAndJqueryDemo/jsonTest/str.action",
dataType: "json",
data: {"name":"pyz","age":"30"},
beforeSend: function(XMLHttpRequest){
//ShowLoading();
$("#str").val("正在处理中...");
},
success: function(data){
alert("字符串:" + data);
},
complete: function(XMLHttpRequest, textStatus){
//HideLoading();
$("#str").val("已处理完成");
},
error: function(){
//请求出错处理
alert("error");
}
});
});

$("#keyValue").click(function(){
$.ajax({
type: "post",
url: "http://localhost:8080/jsonAndJqueryDemo/jsonTest/keyValue.action",
dataType: "json",
data: {"name":"pyz","age":"30"},
beforeSend: function(XMLHttpRequest){
//ShowLoading();
$("#keyValue").val("正在处理中...");
},
success: function(data){
var jo = eval("("+data+")");
alert("姓名:" + jo.name + " 年龄:"+ jo.age);
},
complete: function(XMLHttpRequest, textStatus){
//HideLoading();
$("#keyValue").val("已处理完成");
},
error: function(){
//请求出错处理
alert("error");
}
});
});

$("#objList").click(function(){
$.ajax({
type: "post",
url: "http://localhost:8080/jsonAndJqueryDemo/jsonTest/objList.action",
dataType: "json",
data: {"name":"pyz","age":"30"},
beforeSend: function(XMLHttpRequest){
//ShowLoading();
$("#objList").val("正在处理中...");
},
success: function(data){
var jo = eval("("+data+")");
var buf="" ;
//遍历json返回数据
$(jo).each(function(i,item){
buf += "姓名:";
buf += item.name;
buf += " 年龄:";
buf += item.age;
buf += "/r/n";
});
alert(buf);
},
complete: function(XMLHttpRequest, textStatus){
//HideLoading();
$("#objList").val("已处理完成");
},
error: function(){
//请求出错处理
alert("error");
}
});
});

});

// --></mce:script>
</head>

<body>
<input type="button" id="keyValue" value="提交/接收数据(键值对)" /> <br>
<input type="button" id="str" value="接收字符串" /> <br>
<input type="button" id="objList" value="接收对象列表" /> <br>
</body>
</html>

(二)Action代码

[b][c-sharp]
view plaincopy[/b]

package com.pyz.action;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import com.opensymphony.xwork2.ActionSupport;
@ParentPackage("json-default")
public class JsonTestAction extends ActionSupport {
private static final long serialVersionUID = 1L;

//返回json格式的数据
private String result;

@Action(
value="/jsonTest/str",
results={
@Result(name="success", type="json", params={"root","result"})
}
)
public String str(){
String name = ServletActionContext.getRequest().getParameter("name");
String age = ServletActionContext.getRequest().getParameter("age");

this.result = "aaa";

return SUCCESS;
}

@Action(
value="/jsonTest/keyValue",
results={
@Result(name="success", type="json", params={"root","result"})
}
)
public String keyValue(){
String name = ServletActionContext.getRequest().getParameter("name");
String age = ServletActionContext.getRequest().getParameter("age");

// //方法一,直接创建JSON对象
// JSONObject jo = new JSONObject();
// jo.element("name", name);
// jo.element("age", age);

// //方法二,JAVABEAN转JSON对象
// User user = new User();
// user.setName("pyz");
// user.setAge(19);
// JSONObject jo = (JSONObject)JSONObject.fromObject(user);
// //JSONObject jo = (JSONObject)JSONSerializer.toJSON(user);//等于上语句

//方法三,MAP转JSON对象
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "pyz");
map.put("age", 19);
JSONObject jo = (JSONObject)JSONObject.fromObject(map);
//JSONObject jo = (JSONObject)JSONSerializer.toJSON(user);//等于上语句

this.result = jo.toString();

return SUCCESS;
}
@Action(
value="/jsonTest/objList",
results={
@Result(name="success", type="json", params={"root","result"})
}
)
public String objList(){
String name = ServletActionContext.getRequest().getParameter("name");
String age = ServletActionContext.getRequest().getParameter("age");

//方法一,直接创建JSON对象
JSONObject jo = new JSONObject();
jo.element("name", name);
jo.element("age", age);
JSONObject jo1 = new JSONObject();
jo1.element("name", "ty");
jo1.element("age", "29");

//同理,可以将JAVABEAN、MAP对象转换成JSON对象,再添加到JSONArray中

JSONArray ja = new JSONArray();
ja.add(jo);
ja.add(jo1);
this.result = ja.toString();

return SUCCESS;
}

public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}

public class User{
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: