display arraylist send from spring controller to j

2019-09-07 06:38发布

问题:

I have question model as follows

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

Question List is as follow

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()"));  

In Controller I have passed list as follows

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

In jsp page

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

In json varible data is as follows

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

How can I iterate data??

I can get question,optA and other by following code

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

but i want values of qestions inside js.

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

How Can I do that??

回答1:

You cannot access java arrayList directly on js. You need to use json or xml to access them onto js. When you do var json = "${data}", it just invokes toString function and there is no js equivalent of java list.

In order to circumvent that, you can simply use JSONArray from net.sf.json.JSONArray or for that matter any framework that converts java to json and store it in model attribute.

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

on javascript now, you should be able to access it with js notation.

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