Home > Article > Web Front-end > Ajax+Struts2 receives array form (with code)
This time I will bring you Ajax Struts2 to receive an array form (with code). What are the precautions for Ajax Struts2 to receive an array form? The following is a practical case, let's take a look.
I will explain below through two methods: ordinary form and ajax. First we have the following entity, an action and a jsp.
Student.java
public class Student { private String name; private String num; } StudentAction.java public class StudentAction extends ActionSupport { private List<Student> lstStu; }
xy.jsp
<script type="text/javascript"> var stus = []; stus.push({num:"1",name:"xy1"}); stus.push({num:"2",name:"xy2"}); stus.push({num:"3",name:"xy3"}); </script>
Let’s get started. The following code is written in xy. jsp script area.
Normal form form——Traverse the array, construct the form hidden field
var htmlContent = ""; for(var i=0;i<stus.length;i++){ htmlContent += "<input type='hidden' name='lstStu[" + i + "].name' value='" + stus[i].name + " ' />"; htmlContent += "<input type='hidden' name='lstStu[" + i + "].num' value='" + stus[i].num + " ' />"; }
Special case
<input type='hidden' name='lstStu.name' value='xy1' /> <input type='hidden' name='lstStu.name' value='xy2' /> <input type='hidden' name='lstStu.name' value='xy3' />
When passing a single attribute, struts can recognize it and represent three different students. But passing two attributes won't work, because struts doesn't know the combination. Not recommended.
ajax form - traverse the array and construct a json object
var param = {}; for(var i=0;i<stus.length;i++){ param["lstStu[" + i + "].name"] = stus[i].name; param["lstStu[" + i + "].num"] = stus[i].num; } $.ajax({ data:param });
In fact, we constructed such a json object
data:{ lstStu[0].num:"1",lstStu[0].name:"xy1", lstStu[1].num:"2",lstStu[1].name:"xy2", lstStu[2].num:"3",lstStu[0].name:"xy3" }
I believe you have mastered the method after reading the case in this article, and more How exciting, please pay attention to other related articles on php Chinese website!
Recommended reading:
Detailed explanation of JSONP implementation principles and cases
How to use the ajax.load() method in jQuery
The above is the detailed content of Ajax+Struts2 receives array form (with code). For more information, please follow other related articles on the PHP Chinese website!