改变世界的是这样一群人,他们寻找梦想中的乐园,当他们找不到时,他们亲手创造了它

Js获取后台集合List的值和下标的方法

首先用的是struts2的框架,分两种情况:

1. 集合list里面是值,不是对象,后台代码:

public class myTest {
    ArrayList<String> mylist;
    
    public ArrayList<String> getMylist() {
        return mylist;
    }

    public void setMylist(ArrayList<String> mylist) {
        this.mylist = mylist;
    }

    public String test(){
        mylist = new ArrayList<String>();
        mylist.add("aa");
        mylist.add("bb");
        mylist.add("cc");
        mylist.add("dd");
        return "success";
    }
}

前台代码:

 

首先,引入相应的标签和js库

1)引入jstl标签库,<%@taglib uri="http://Java.sun.com/jsp/jstl/core" prefix="c"%>

2)引入jQuery库,<script type="text/JavaScript" src="js/jquery.js"></script>

 (3)js代码:

<script type="text/javascript">
    var array = new Array();
    //console.info("info");
    <c:forEach items="${mylist}" var="item" varStatus="status" >
        array.push("${item}");
        //获得值
        alert("${item}");
        //获得其下标
        alert("${status.count}");
        //var temp = "${item}";
    </c:forEach>
    for(var i=0;i<array.length;i++){
        alert(array[i]);
    }
    
</script>

2.集合list中是对象,不是值

1)后台代码:

 

package com.beans;

public class Dog {
    String name;
    int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

public class myTest {
    ArrayList<Dog> mylist;

    public ArrayList<Dog> getMylist() {
        return mylist;
    }

    public void setMylist(ArrayList<Dog> mylist) {
        this.mylist = mylist;
    }

    public String test(){
        mylist = new ArrayList<Dog>();
        Dog dog1 = new Dog();
        Dog dog2 = new Dog();
        dog1.setName("wangwang");
        dog1.setAge(121);
        dog2.setName("miaomiao");
        dog2.setAge(151);
        mylist.add(dog1);
        mylist.add(dog2);
        return "success";
    }

}

 

2Js代码:

 

<script type="text/javascript">
    var array = new Array();
    //console.info("info");
    <c:forEach items="${mylist}" var="item" varStatus="status" >
        array.push("${item}");
        var temp = "${item}";
        //获得其下标
        alert("${status.count}");
        //传递过来的是字符串,加引号
        alert("${item.name}");
        //传递过来的是int类型,不需要加引号
        alert(${item.age});
    </c:forEach> 
</script>

 

posted @ 2018-01-02 18:00  水狼一族  阅读(29826)  评论(0编辑  收藏  举报
改变世界的是这样一群人,他们寻找梦想中的乐园,当他们找不到时,他们亲手创造了它