1

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 Answer 1

2

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);
         });
Sign up to request clarification or add additional context in comments.

2 Comments

I tried that but I am getting following TypeError: invalid 'in' operand a localhost:8080/in/resources/js/jquery.min.js Line 2
@NewBuddy I am sorry. I overlooked you trying to parse a java arrayList directly. I have edited my answer. This should give you the gist of it. Let me know if you run into any issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.