如何使用jQuery将JSON数据发布到Struts2 Action类 [英] How to use jQuery to post JSON data to a Struts2 Action class

查看:170
本文介绍了如何使用jQuery将JSON数据发布到Struts2 Action类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将数据从jQuery发送到struts2动作类时遇到了问题。
我看到了一个问题: JSON Jquery对Struts2的行动但我不知道我不太了解解决方案。

I've a problem sending data from jQuery to struts2 action class. I have seen the question: JSON Jquery to Struts2 action but I don't understand the solution quite well.

这是我的问题:

json数组是这样的:

The json array is like this:

[{"id":"1","code":"111","name":"ddd"},
 {"id":"2","code":"222","name":"sss"},
 {"id":"3","code":"333","name":"eee"}]

我想将json数据发送到struts2动作课。
jQuery代码是这样的:

I want to send the json data to the struts2 action class. The jQuery code is like this:

var data = JSON.stringify(dataObj);
$.ajax({
  url: "Update",
  type: "post",
  data:  data,
  dataType: 'json',
  contentType:"application/json;charset=utf-8",
  success : function(){
    alert("You made it!");
  }
});

但是,在Chrome的开发工具中,我看到了提交给服务器端的数据。但在服务器端,我不知道如何接收json数据。

However, in Chrome's Development Tool, I have seen the data submitted to the server side. But on the server side, I don't know how receive the json data.

行动:

public class Update extends ActionSupport{
    private String data;

    public String getData(){
        return data;
    }

    public void setData(String data){
        this.data= data;
    }

    public String execute(){
        System.out.println(data);
        return SUCCESS;
    }
}

这样,数据为空。

我还尝试使用List来接收JSON数据。将数据类型从字符串更改为列表<节点> ,它再次失败。可能是因为我不太了解Struts2正在使用的OGNL模型。

I've also tried to use a List to receive JSON data. Changing "data" type from String to List<Node>, it failed again. Probably because I don't quite understand the OGNL model which Struts2 is using.

请帮助我。非常感谢!

推荐答案

{"id":"1","code":"111","name":"ddd"}

第1步:创建bean / pojo用于累积/封装上述字段

class MyBean{
    String id,code,name;
    //getters & setters
}

第2步:更改您的操作代码以接收List of MyBeans

public class Update extends ActionSupport{
    private List<MyBean> data;

   //other code, getters & setters
}

步骤3:配置您的操作以反序列化JSON数据并填写操作字段(使用json-plugin)

    <action name="Update" class="Update">
        <interceptor-ref name="defaultStack"/>
         <interceptor-ref name="json">
            <param name="enableSMD">true</param>
        </interceptor-ref>
</action>

步骤4:在发送的ajax请求正文中进行必要的更改以匹配操作 - 参数/字段

var data = JSON.stringify(dataObj);
$.ajax({
  url: "Update",
  type: "post",
  data:  "data:"+data,
  dataType: 'json',
  contentType:"application/json;charset=utf-8",
  success : function(){
    alert("You made it!");
  }
});

以上代码未经测试。

这篇关于如何使用jQuery将JSON数据发布到Struts2 Action类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆