Reputation: 15
I want to send a list of User object into action, while user has field name and address here.
Some code like this: The webpage is dynamic manipulated by jquery. there is sample code of webpage.
<form id="create">
<tr id="1"> <td> <input type='text' name='name'/></td><td><input type='text' name='address'/></td></tr>
<tr id="3"> <td> <input type='text' name='name'/></td><td><input type='text' name='address'/></td></tr>
</form>
<input type='submit' onclick="submit()"/>
<script>
function submit() {
var results = [];
$("#create tr").each(function(index, tr) {
var user = {
name: tr.find('input[name="name"]').val(),
address: tr.find('input[name="address"]').val()
}
results.push(user);
});
var param = {users:results};
$.ajax({
url: "save.action",
data: param,
type: 'post',
success: function() {
alert('success');
},
error: function() {
alert('error');
}
});
}
</script>
Action code like this:
@ParentPackage('json-default')
public class UserAction extends ActionSupport {
private List<User> users;
public List<User> getUsers(){
return users;
}
public void setUsers(List<User> users){
this.users = users;
}
@Action(name="save", results={@Result{name="success",location="/webpage/addUser.jsp"}})
public String execute(){
for(User user: Users){
System.out.println(user.getName()+" address: "+ user.getAddress());
}
return SUCCESS;
}
}
My question is why the action can't receive the data? I capture the data from firebug and the data has been posted. So any hint or something wrong? I was confused here two days, please help.
Upvotes: 0
Views: 3128
Reputation: 1591
Can you post the rest of your jsp, action and exactly what you are posting back to your action. Without seeing the rest I would guess that you are not handling in-situ list updating correctly. If you were using "traditional" HTML I would expect to see a reference to the users list index in both the HTML and the returned data so that Struts knows which list elements to update/create.
Regards
Upvotes: 0
Reputation: 11055
If Firebug is indicating that the data is being successfully posted, then I would recommend that you do some debugging on the Java side to confirm that.
Try placing a break point and viewing the actual HttpServletRequest
parameters that are coming in to make sure that they are being set properly. If they are, then make sure that your setUsers(List<User> user)
method is being called. This should point out exactly where the failure is occurring.
Upvotes: 0
Reputation: 75147
If you use jQuery 1.4 you should consider that there is a change about param serialization. JQuery provides a new flag in $.ajax to override the default behavior (and go back to use the old way of param serialization): the "traditional" option in $.ajax So you should try that to send data over Ajax at JQuery:
....
$.ajax({
url:"save.action",
data:param,
type:'post',
traditional: true,
....
Upvotes: 1