通过异步请求返回json格式的数据,然后组装,在界面显示
?
?
import net.sf.json.JSONArray; import net.sf.json.JSONObject; import com.opensymphony.xwork2.ActionSupport; public class JsonAjax extends ActionSupport { private static final long serialVersionUID = -6745063993271552844L; //返回json格式的数据 private String result; /** * 处理方法 * @return * @throws Exception * @create_time 2011-5-30 下午04:47:34 */ public String jsonAjaxExample()throws Exception{ JSONObject obj=new JSONObject(); JSONObject obj1=new JSONObject(); obj.element("name", "yao"); obj.element("age", "20"); obj1.element("name", "laughing"); obj1.element("age", "5"); JSONArray array=new JSONArray(); array.add(obj); array.add(obj1); StringBuffer sb=new StringBuffer(); sb.append("{member:"); sb.append(array); sb.append("}"); result=sb.toString(); return SUCCESS; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } }
?
xml代码
?
<package name="json" extends="json-default"> <action name="jsonAjax" class="com.aicaipiao.ggtj.action.base.JsonAjax" method="jsonAjaxExample"> <!-- 返回类型为json 在json-default中定义 --> <result name="success" type="json"> <!-- root的值对应要返回的值的属性 --> <!-- 这里的result值即是 对应action中的 result --> <param name="root">result</param> </result> </action> </package>?
html代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" /> <title>json ajax example</title> <script type="text/javascript" src="js/jquery-1.4.2.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#json").click(function(){ $.ajax({ url:"jsonAjax.html", type:"post", dataType:"json", data:"", error:function(){ }, success:function(data){ var value=eval("("+data+")"); var buf="" ; //遍历json返回数据 $(value.member).each(function(i,mem){ buf+="<li>姓名:"; buf+=mem.name; buf+="---年龄:"; buf+=mem.age; buf+="</li>"; }); $("#jsonAjaxResult").append(buf); } }); }); }); </script> </head> <body> <table> <tr> <td><input type="button" id="json" value="json例子" name="json"/></td> </tr> </table> <div > <ul id="jsonAjaxResult"></ul> </div> </body> </html>?
?