通过JSON对象迭代的JSP Servlet Ajax调用(MVC)

时间:2018-06-26 17:41:13

标签: javascript json ajax jsp servlets

$(document).ready(function() {       
        $.get("/myServlet", function(responseJson) {                 
            var $container = $("#mySpace");
            var x = "";

            $.each(responseJson, function(key,value) {  
                var object = JSON.stringify(value);

                x+= " . "+object+"<br>";
             });
            $container.append(x);


        });
    });

//--------------------------------------------- -Servlet ---------- ----

   protected void doGet(HttpServletRequest request, HttpServletResponse 
 response) throws ServletException, IOException {

  ArrayList<Students> list = new ArrayList<>();

  Student s = new Student();
  s.setid(1);
  s.setName("john");
  s.setYear(5.5);

  Student s1 = new Student();
  s1.setid(2);
  s1.setName("alice");
  s1.setYear(5.5);

  Student s2 = new Student();
  s2.setid(3);
  s2.setName("nami");
  s2.setYear(3.5);

  list.add(s);
  list.add(s1);
  list.add(s2);

        String json = new Gson().toJson(list);
         response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(json);

}

我在javascript中的x产生了这个。即使当我尝试访问object [“ id”]例如x + =“。” + object [“ id”] +“
”;我无法。它说未定义。有什么建议吗?还是应该使用在此创建的学生模型? (不确定如何)

容器的输出:

。 {“ id”:1,“ name”:“ john”,“ year”:5.5}

。 {“ id”:2,“ name”:“ alice”,“ year”:5.5}

。 {“ id”:3,“ name”:“ nami”,“ year”:3.5}

1 个答案:

答案 0 :(得分:1)

希望这会起作用。

$(document).ready(function() {          
        $.get("/myServlet", function(responseJson) {
        var $container = $("#mySpace");
        var x = "";
        var jsonData = JSON.parse(responseJson);
                $.each(jsonData, function(key,value) { 
                    x+= " . "+value.id+" "+value.name+" "+value.year+"<br>";
                 });
                 console.log(x);
                 $container.append(x);
          });
    });