jquery1.4.4 ajax json 在struts2.2.1中没法封装对象,求解脱

才学着用jquery的ajax,用json封装对象在action中找不到,求大神帮看下:
js:
[code="java"]
$("#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);
                    }
                }); 
            }
        });

[/code]

上面是js部分
[code="java"]

<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>

[/code]

[code="java"]
@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
[/code]

死活出不来

这个包:
commons-collections-3.2.jar
commons-lang-2.3.jar
commons-logging-1.0.4.jar
ezmorph-1.0.3.jar
json-lib-2.1-jdk15.jar
struts2-json-plugin-2.2.1.jar

[code="java"]
2010-12-30 10:51 WARN c.j.c.h.HibernateSessionFilter - HibernateSessionFilter begin doChain
进来了,我是JSON...............
Soms4CdnAccessMethods...............
methods.name=null
[/code]

证明是能进action的 但前面ajax总是error
data用para也能进action,但idList总是第一个有值
[code="java"]
2010-12-30 10:56 WARN c.j.c.h.HibernateSessionFilter - HibernateSessionFilter begin doChain
进来了,我是JSON...............
list长度===1
idList[0]=["0","5"]
get Method Id from ajax json:["0","5"]
json return ==success
[/code]

这是怎么回事?
向各位大神求教..
急 急 急

9个回答

var para1 = {"methods.methodId":"5","methods.methodName":"1"};这种传参方式是无法传对象过去的,跟你配置和用什么技术没啥关系,我是没传成功过,起码我常用的jQuery的高级封装方法$.get 和$.post 是没成功过。
我的方法怎么会不行呢 ,不可能的事儿呀 :cry: 。我们经常用这个种方式啊 data :"methods.methodId=5&methods.methodName=1";

你仔细检查一下,我用那种方法写从来都是可以的。
我还有一种本方法,这个是当你需要穿多个参数的时候用的,
将你的参数放到input里 用form包起来 如:


你的js参数改成 data : $('#myform).serialize(),

我一般是这么用,挺简单的:
1、Action方法
[code="java"]
/**

  • 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();
    }
    }
    [/code]

2、struts配置
[code="xml"]






[/code]

3、页面使用jQuery的ajax封装函数进行ajax调用,很方便
var weekUrl = basePath + "/findAllWeeks.action";
$.post(weekUrl, {参数名:参数值, 参数名1:参数值1}, function(data){
if (data) {
alert(data.a + " " + data.b);
}
}, "json");

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.

使用方法:
[code="java"]
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);

    // List
    List<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);

    // Map
    Map<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);
}

}

[/code]

Struts2.1.6默认没支持

可的result类型json
2.2.1支持吗?

刚查看了2.2.1.1版本,支持的result-type如下:
[code="xml"]












[/code]

明白了,你使用了struts的json插件包,默认下载的时候,会自带相应的包,一般都是兼容后才发布的,如:

struts2-core-2.2.1.1.jar
struts2-json-plugin-2.2.1.1.jar

1.4.4比较新,没用,现在用1.3.2,感觉比较稳定,ajax使用没问题

配置似乎没问题,你试试将
methods.*
中的methods.*配置为methods.属性1,methods.属性2
试试

实在不行就这么写
var para1 = "methods.methodId=5&methods.methodName=1";

应该没问题

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!