struts2 返回json数据,jquery解析
表结构:
CREATE TABLE IF NOT EXISTS `random` (
???? `id` int( 11 ) NOT NULL AUTO_INCREMENT ,
???? `name` varchar( 50 ) NOT NULL ,
???? PRIMARY KEY ( `id` )
?? ) ENGINE = MYISAM DEFAULT CHARSET = utf8 AUTO_INCREMENT =1
Struts2.xml文件
<package name="json" extends="json-default" namespace="/random"><global-results><result name="exception">/error.jsp</result></global-results><global-exception-mappings><exception-mapping exception="java.lang.Exception" result="exception" /></global-exception-mappings><action name="json" method="jsonTest" name="code">public String jsonTest(){HttpServletRequest request = ServletActionContext.getRequest();HttpServletResponse response = ServletActionContext.getResponse();// HttpSession session = request.getSession();String id = request.getParameter("flag");List<RandomObj> objList = randomService.getRandomObj(Integer.parseInt(id));JSONArray array = JSONArray.fromObject(objList);this.result = array.toString();System.out.println(result);return Action.SUCCESS;}private String result;public String getResult() {return result;}public void setResult(String result) {this.result = result;}
?JS
$(document).ready(function(){var id = $("#flagId").val();if(id == 50)window.setTimeout(function(){selectData3()},0);function selectData3(){var id = $("#flagId").val();$.ajax({ type: "POST", url: "random/json.action", dataType : "json", data: "flag="+id, success: function(result){ var json = eval( "("+result+")" );var temp_html=""; $.each(json,function(i,n){ //alert(json[i].id+json[i].name); if(i == 0){ $("#flagId").val(json[i].id); } temp_html += "<li>"+json[i].id+"========"+json[i].name+"</li>"; }); $("#aaa").after(temp_html); }});}window.setInterval(function(){selectData3()},60000);})
?JSP
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <SCRIPT language=javascript src="js/jquery-1.2.6.js"></SCRIPT> <SCRIPT language=javascript src="js/myjson.js"></SCRIPT> </head> <body> <a href="random/cache.action">cache</a> <a href="json.jsp">json</a> <a href="index.jsp">index.jsp</a> <input type="hidden" id="flagId" name="flagId" value="50"> <div id="aaa" align="center" ></div> </body></html>?
?
1 楼 yjmyd1119 2012-01-13 不错,不错。