简体   繁体   中英

How to post an array of JSON objects to a Struts2 action using jQuery?

Using Struts2. In my Action I have a List<Person> persons;

In javascript, I have this function:

function mytestfunction() {
    var url = "MyAction_mytestfunction.action";
    var params = {};
    var arr = [];
    var p1 = { "firstname" : "John", "lastname" : "Doe"};
    var p2 = { "firstname" : "Rob", "lastname" : "Smith"};
    arr.push(p1); arr.push(p2);
    params["persons"] = arr;
    $.post(url, params, function(data) {
        console.log("done");
    });
}

Problem is, the post() never reaches the action. There are no errors in the logs, nothing.

This all changes if instead of posting objects I post primitives. So when I have a List<Integer> nums in the Action and params["nums"] = [1,2,3]; in javascript, everything is posted fine.

So, is there a way to post JSON objects to a Struts2 action via javascript/jquery?

I should mention that I'm using the struts-jquery plugin, not dojo.

I don't know anything about struts, but this is how I POST objects with json:

$.ajax({
    type: "POST",
    data: JSON.stringify(SOME_JAVASCRIPT_OBJECT),
    contentType: "application/json; charset=utf-8"
    // etc: etc
});

you can try as following example:

$.ajax({
       type: "Post",
    url: "action_name",    //you can pass through querystring like actionname?paramname=value
    data : {
           //here comes your param or array 
        },
    dataType:"json",
    contentType: "application/json; charset=utf-8",
});

If you want to pass through querystring type must be GET

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM