显示arraylist从spring controller发送到jsp

时间:2015-03-19 17:58:44

标签: jquery spring-mvc

我的问题模型如下

public class Question{
    String question;
    String optA;
    String optB;
    String optC;
    String optD;
    //getter and setter
}

问题清单如下

questionList = new ArrayList<Question>();
        questionList.add(new Question("Which of these method is used to find out that a thread is still running or not?"," checkRun()"," Run()","Alive()","isAlive()"));  
        questionList.add(new Question(" Which of these method waits for the thread to treminate?"," Run()","Alive()","sleep()","join()"));  

在控制器中我已经通过如下列表

model.addAttribute("data", questionManager.getQuestionList());

在jsp页面

var json = "${data}";
         $.each(json, function (index, item) {
        console.log("qustions"+item);
         });

在json中,varible数据如下

var json = "[com.hello.in.model.Question@405b7c, com.hello.in.model.Question@9393a9]";

如何迭代数据?

我可以通过以下代码获得问题,optA和其他

 <c:forEach items="${data}" var="question">
            ${question.question}<br>
        </c:forEach> 

但我想要js中的问题值。

$( document ).ready(function() {
//I want here coz i want to do some processing
}

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您无法直接在js上访问java arrayList。您需要使用json或xml将它们访问到js。执行var json = "${data}"时,它只调用toString函数,并且没有js等效于java list。

为了规避这一点,您可以简单地使用net.sf.json.JSONArray中的JSONArray,或者将任何将java转换为json并将其存储在模型属性中的框架。

model.addAttribute("data", new JSONArray().addAll(questionManager.getQuestionList()));

现在在javascript上,您应该可以使用js表示法访问它。

        var json = JSON.parse("${data}");
         $.each(json, function (index, item) {
          alert(item.question);
          alert(item.optA);
         });