标签:
转载请注明出处:jiq?钦‘s
technical Blog
最近在自己写分布式注册中心的Web管理界面,需要点击左边树节点时,请求后台Action查询该节点的详细数据,然后异步刷新右边的节点信息区域。
异步刷新用了Jquery对Ajax的封装:
function zTreeOnClick(event, treeId, treeNode) { $.ajax({ type: "POST", url: "Config.action", data: "", dataType: "json", success: function(data) { alert(eval("("+data.result+")").word); //$("#configInfo").load("nodeInfo.jsp"); //$("div .configInfo").html(responseText); }, error: function() { $("#configInfo").load("error.jsp"); } }); };
@SuppressWarnings("serial") public class ConfigManageAction extends ActionSupport { private String result; @Override public String execute() throws Exception { Map<String,Object> map = new HashMap<String,Object>(); map.put("word", "word_A"); map.put("wordcount",33); JSONObject json = JSONObject.fromObject(map); this.result = json.toString();//给result赋值,传递给页面 return SUCCESS; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="struts-default,json-default"> <action name="Login" class="org.zk.action.LoginAction"> <result name="success">/index.jsp</result> <result name="error">/error.jsp</result> </action> <action name="test" class="org.zk.action.ConfigManageAction" method="method"/> <action name="Config" class="org.zk.action.ConfigManageAction"> <result name="success" type="json" /> </action> </package> </struts>
public String method() throws Exception { HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("application/json;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter pw = response.getWriter(); Map<String,Object> map = new HashMap<String,Object>(); map.put("word", "word_A"); map.put("wordcount",33); JSONObject json = JSONObject.fromObject(map);//将map对象转换成json类型数据 pw.write(json.toString()); pw.flush(); pw.close(); return null; }
必须要去查看页面请求返回的结果,打开chrome进入到管理界面,按F12 出来调试界面。
点击树节点,在Network这个Tab页查看所有请求和对应的回应,发现虽然Config.action请求返回码是200,即正常,但是response却全是异常!!!
然后逐个排除这些异常,基本上全是因为少Jar包,最后jar包如下:
这下就返回success了,但是解析返回的JSON字符串却总是错误,我的返回如下:
然后再网上查到能够解析的json应该是这样:{‘key1‘:‘value1‘},并且用形如:
var obj = eval( "(" + strJSON + ")" );//转换后的JSON对象 alert(obj.name);//json name
alert(eval("("+data.result+")").word);
标签:
原文地址:http://blog.csdn.net/jiyiqinlovexx/article/details/43106413