Home  >  Article  >  Web Front-end  >  Ajax+Struts2 receives array form (with code)

Ajax+Struts2 receives array form (with code)

php中世界最好的语言
php中世界最好的语言Original
2018-04-25 16:10:201589browse

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=&#39;hidden&#39; name=&#39;lstStu[" + i + "].name&#39; value=&#39;" + stus[i].name + " &#39; />";
 htmlContent += "<input type=&#39;hidden&#39; name=&#39;lstStu[" + i + "].num&#39; value=&#39;" + stus[i].num + " &#39; />";
}

Special case

<input type=&#39;hidden&#39; name=&#39;lstStu.name&#39; value=&#39;xy1&#39; />
<input type=&#39;hidden&#39; name=&#39;lstStu.name&#39; value=&#39;xy2&#39; />
<input type=&#39;hidden&#39; name=&#39;lstStu.name&#39; value=&#39;xy3&#39; />

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn