display arraylist send from spring controller to j

2019-09-07 07:12发布

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条回答
一夜七次
2楼-- · 2019-09-07 07:22

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);
         });
查看更多
登录 后发表回答