问题描述
才学着用jquery的ajax,用json封装对象在action中找不到,求大神帮看下:js:$("#editViewMethod").click(function(){var ids = "";var flag = 0;var jsonStr = "";$("input[type='checkbox'][name!='checkAll']").each(function(){if($(this).attr("checked")){flag = flag + 1;ids = ids+","+$(this).attr("value");}});if(flag == 0){alert("您没有选择!");}else if(flag > 1){alert("请选择一条记录!");}else{alert("ids="+ids);jsonStr = '["0","5"]';//alert(jsonStr);//$.post("delServerMethod.do",{"idList":jsonStr}, delMethod,"json");var para = {"idList":"["0","5"]"};var para1 = {"methods.methodId":"5","methods.methodName":"1"}; var p = jQuery.parseJSON(para1);$.ajax({type: "POST",url: "json/editServerMethod.do",data: para1,dateType:"json",error: function(){alert("Error loading json Object");},success: function(data){alert(data);//$.each(json,function(i,n){//alert("Key:"+i);//alert("Value:"+n);//});//var jsonMsg = JSON.stringify(json);//alert(jsonMsg);alert(data.methods.methodId);}}); }}); 上面是js部分<!--jquery ajax json --><package name="ajaxJson" namespace="/soms_sys/cdn/serverManager/json" extends="json-default" ><action name="delServerMethod" method="delServerMethod" class="com.jwzt.soms.cdn.action.CdnServMethodAct"><result name="del_success" type="json"><param name="includeProperties">message</param></result></action><action name="editServerMethod" method="editServerMethod" class="com.jwzt.soms.cdn.action.CdnServMethodAct"><result name="edit_success" type="json"><param name="includeProperties">methods.*</param><param name="excludeProperties">methods.soms4CdnServer</param></result></action></package>@SuppressWarnings("serial")public class CdnServMethodAct extends JeeCoreAction{protected static Logger logger = LoggerFactory.getLogger(CdnServerAct.class);private Soms4CdnAccessMethods methods;private List<String> idList;private String ids;private String message;public String delServerMethod(){String id = idList.get(0);//methods.getMethodId();System.out.println("get Method Id from ajax json:"+id);this.setMessage("success");System.out.println("json return =="+this.getMessage());idList = new ArrayList<String>();idList.add("1");idList.add("2");return "del_success";}public String editServerMethod(){String id = idList.get(0);//methods.getMethodId();System.out.println("get Method Id from ajax json:"+id);this.setMessage("success");System.out.println("json return =="+this.getMessage());idList = new ArrayList<String>();idList.add("1");idList.add("2");methods.setMethodId(5);methods.setMethodName("test");return "edit_success";}public Soms4CdnAccessMethods getMethods(){return methods;}public void setMethods(Soms4CdnAccessMethods methods){System.out.println("进来了,我是JSON...............");System.out.println("Soms4CdnAccessMethods...............");System.out.println("methods.name="+methods.getMethodName());this.methods = methods;}public List<String> getIdList(){return idList;}public void setIdList(List<String> idList){System.out.println("进来了,我是JSON...............");System.out.println("list长度==="+idList.size());System.out.println("idList[0]="+idList.get(0));this.idList = idList;}//setter or getter 死活出不来这个包:commons-collections-3.2.jarcommons-lang-2.3.jarcommons-logging-1.0.4.jarezmorph-1.0.3.jarjson-lib-2.1-jdk15.jarstruts2-json-plugin-2.2.1.jar2010-12-30 10:51 WARN c.j.c.h.HibernateSessionFilter - HibernateSessionFilter begin doChain进来了,我是JSON...............Soms4CdnAccessMethods...............methods.name=null证明是能进action的 但前面ajax总是errordata用para也能进action,但idList总是第一个有值 2010-12-30 10:56 WARN c.j.c.h.HibernateSessionFilter - HibernateSessionFilter begin doChain进来了,我是JSON...............list长度===1idList[0]=["0","5"]get Method Id from ajax json:["0","5"]json return ==success这是怎么回事?向各位大神求教..急 急 急 问题补充:zhanjia 写道
解决方案
var para1 = {"methods.methodId":"5","methods.methodName":"1"};这种传参方式是无法传对象过去的,跟你配置和用什么技术没啥关系,我是没传成功过,起码我常用的jQuery的高级封装方法$.get 和$.post 是没成功过。我的方法怎么会不行呢 ,不可能的事儿呀 。我们经常用这个种方式啊 data :"methods.methodId=5&methods.methodName=1"; 你仔细检查一下,我用那种方法写从来都是可以的。我还有一种本方法,这个是当你需要穿多个参数的时候用的,将你的参数放到input里 用form包起来 如:<form id="myform"><input name="methods.methodId" value="2" type="hidden"/></form>你的js参数改成 data : $('#myform).serialize(),
解决方案二:
实在不行就这么写var para1 = "methods.methodId=5&methods.methodName=1"; 应该没问题
解决方案三:
配置似乎没问题,你试试将<param name="includeProperties">methods.*</param>中的methods.*配置为methods.属性1,methods.属性2试试
解决方案四:
1.4.4比较新,没用,现在用1.3.2,感觉比较稳定,ajax使用没问题
解决方案五:
明白了,你使用了struts的json插件包,默认下载的时候,会自带相应的包,一般都是兼容后才发布的,如:struts2-core-2.2.1.1.jarstruts2-json-plugin-2.2.1.1.jar
解决方案六:
刚查看了2.2.1.1版本,支持的result-type如下:<result-types> <result-type name="chain" class="com.opensymphony.xwork2.ActionChainResult"/> <result-type name="dispatcher" class="org.apache.struts2.dispatcher.ServletDispatcherResult" default="true"/> <result-type name="freemarker" class="org.apache.struts2.views.freemarker.FreemarkerResult"/> <result-type name="httpheader" class="org.apache.struts2.dispatcher.HttpHeaderResult"/> <result-type name="redirect" class="org.apache.struts2.dispatcher.ServletRedirectResult"/> <result-type name="redirectAction" class="org.apache.struts2.dispatcher.ServletActionRedirectResult"/> <result-type name="stream" class="org.apache.struts2.dispatcher.StreamResult"/> <result-type name="velocity" class="org.apache.struts2.dispatcher.VelocityResult"/> <result-type name="xslt" class="org.apache.struts2.views.xslt.XSLTResult"/> <result-type name="plainText" class="org.apache.struts2.dispatcher.PlainTextResult" /> </result-types>
解决方案七:
Struts2.1.6默认没支持<result name="edit_success" type="json">可的result类型json2.2.1支持吗?
解决方案八:
1、只要拼装好json字符串,写到输出流就行了2、后台可借助json-lib-2.2.3-jdk15.jar包对List、Bean等直接转为json字符串1)、JSON-lib is a java library for transforming beans, maps, collections, java arrays and XML to JSON and back again to beans and DynaBeans.It is based on the work by Douglas Crockford in http://www.json.org/java . 2)、CAUTION: when parsing, JSONObject and JSONArray will check for cycles in the hierarchy, throwing an exception if one is found. You can change this behavior by registering a CycleDetectionStrategy.使用方法:package json.test;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import json.bean.MyBean;import net.sf.json.JSONArray;import net.sf.json.JSONObject;public class FirstTest {/** * 简化System.out.println * * @param obj */public static void out(Object obj) {System.out.println(obj);}/** * @param args */public static void main(String[] args) {// boolean数组boolean[] boolArray = new boolean[] { true, false, true };JSONArray jsonArray = JSONArray.fromObject(boolArray);out(boolArray + "结果:" + jsonArray);// ListList<String> list = new ArrayList<String>();list.add("first");list.add("second");JSONArray jsonArray1 = JSONArray.fromObject(list);out(list + "结果:" + jsonArray1);// String[]JSONArray jsonArray2 = JSONArray.fromObject("['json','is','easy']");out(jsonArray2);// MapMap<String, Object> map = new HashMap<String, Object>();map.put("name", "json");map.put("bool", Boolean.TRUE);map.put("int", new Integer(1));map.put("arr", new String[] { "a", "b" });map.put("func", "function(i){ return this.arr[i]; }");JSONObject jsonObject = JSONObject.fromObject(map);out(jsonObject);}}
解决方案九:
我一般是这么用,挺简单的:1、Action方法/** * Action方法 */public String findAllWeeks() { String jsonString = "{a:1,b:2}"; // 构建一个json字符串 writeToOutputStream(jsonString, "将json结果字符串写到输出流"); return NONE; } /** * 将字符串写到输出流 * * @param str 要输出的字符串 * @param msg 操作信息字符串, 用于出错时写日志 * @return boolean 成功时为true, 否则为false */ protected boolean writeToOutputStream(String str, String msg) { HttpServletResponse response = ServletActionContext.getResponse(); response.setCharacterEncoding("UTF-8"); PrintWriter writer = null; try { writer = response.getWriter(); writer.write(str); writer.flush(); return true; } catch (Exception e) { log.error(msg + "时发生错误!", e); return false; } finally { writer.close(); } } 2、struts配置<package name="yourPackage" extends="default" namespace="yourNamespace"> <action name="findAllWeeks" class="YourAction" method="findAllWeeks" /> </package> 3、页面使用jQuery的ajax封装函数进行ajax调用,很方便 var weekUrl = basePath + "/findAllWeeks.action"; $.post(weekUrl, {参数名:参数值, 参数名1:参数值1}, function(data){ if (data) { alert(data.a + " " + data.b); } }, "json");