简体   繁体   English

如何从控制器返回对象列表并使用JQuery显示它们(Spring MVC,ajax)

[英]How to return list of objects from controller and display them using JQuery (Spring MVC, ajax)

First, this is my controller: 首先,这是我的控制器:

@Controller
public class MainController {
   @Autowired
   SqlSession sqlSession;
   @Autowired
   Message messageVO;


@RequestMapping(value="getMessages", method=RequestMethod.GET)
public @ResponseBody List<Message> getMessages(HttpSession session){
    JbuserDAO dao = sqlSession.getMapper(JbuserDAO.class);
    List<Message> inboxList = null;
    String logedinUserId = (String) session.getAttribute("loginId");
    inboxList = dao.getInboxList(logedinUserId);
    System.out.println(inboxList);       //I do get the list here so it's not sql problem. I think.
    return inboxList;
}

and this is my JQuery: 这是我的JQuery:

$(function(){
   viewingInbox();
   $("#viewInbox").on('click', function(){
        viewingInbox();
    });
  });


function viewingInbox(){

   $.ajax({
        url: "getMessages"
      , method: "GET"
      , dataType: "JSON"
      , contentType: "application/json; charset=UTF-8"
      , success: function(obj){
        alert(obj.inboxList);      //I get undefined here
        messageInbox(obj);
      }
  });
}


function messageInbox(obj){
   var list = '<div>';
   $(obj.inboxList).each(function(i, item){
       list = list + '<article class="media">'
                  + '<span class="pull-left"><input type="checkbox" class="checkboxes"></span>'
                  + '<span class="pull-left thumb-sm"><img src="resources/images/a2.png" alt="..."></span>'
                  + '<div class="media-body">'
                  + '<div class="pull-right media-xs text-center text-muted">'
                  + '<strong class="h4">12:18</strong><br></div>'
                  + '<a href="#" class="h4">123'+item.sendidjbuser+'</a>'
                  + '<small class="block m-t-sm">'+item.message+'</small></div></article>'
   });
      list = list + '</div>';
      alert(list);               //here I get only <div></div>
      $("#inboxDiv").html(list);
      alert("messageInbox end");
}

What I'm trying to do is to get saved messages from DB and return them as a list of Message VO I made and then print them out on jsp. 我想做的是从数据库获取保存的消息,并将它们作为我制作的消息VO的列表返回,然后在jsp上打印出来。 I thought this was the way to do it but I don't think I'm getting the list from the controller. 我以为这是做到这一点的方法,但是我不认为我从控制器那里得到了清单。 I tried putting alert(message) inside the each statement, and it didn't work; 我尝试将Alert(message)放入每个语句中,但没有用; no alert messages. 没有警报消息。 That means I'm not getting the list from the controller. 这意味着我没有从控制器获取列表。 Am I missing something? 我想念什么吗?

I jave json-databind dependency added, but that's everything I have concerning json. 我添加了json-databind依赖关系,但这就是我所关心的json。

I only learned Strut2 for a month and only recently started using Spring so I must have made stupid mistake I don't know. 我只学习了一个月的Strut2,直到最近才开始使用Spring,所以我一定犯了我不知道的愚蠢错误。 Please tell me what that is. 请告诉我那是什么。 Thanks in advance. 提前致谢。

Problem solved. 问题解决了。 Unlike Struts2, I didn't have to do like this: 与Struts2不同,我不必这样做:

$(obj.inboxList).each(function(i, item){

I think in Struts2 I had to put obj.inboxList because on the action side there are getter and setters. 我认为在Struts2中,我必须放入obj.inboxList,因为在操作方面有getter和setter。

In Spring, there are no getter and setters so maybe, really maybe because I'm just guessing here, that's why just using obj works: 在Spring中,没有getter和setter,所以也许真的是因为我只是在这里猜测,这就是为什么仅使用obj起作用的原因:

$(obj).each(function(i, item){

You can use ResponseEntity as return element and can also convert your list to json list so that jquery can interpret it as iterative element. 您可以使用ResponseEntity作为返​​回元素,也可以将列表转换为json列表,以便jquery可以将其解释为迭代元素。

    @RequestMapping(value="getMessages", method=RequestMethod.GET)
    public ResponseEntity<String> getMessages(HttpSession session){
        JbuserDAO dao = sqlSession.getMapper(JbuserDAO.class);
        List<Message> inboxList = null;
        String logedinUserId = (String) session.getAttribute("loginId");
        inboxList = dao.getInboxList(logedinUserId);


  com.google.gson.Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        String jsonString = gson.toJson(inboxList);
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");
        return new ResponseEntity<String>(jsonString, responseHeaders, HttpStatus.CREATED); 


    }

This way you will definitely get list of your message as you want. 这样,您肯定会获得所需的消息列表。 PS: i haven't gone through your rest of the code. 附言:我没有讲完其余的代码。 But things like the following should work: 但是类似以下的事情应该起作用:

success: function(obj){

 $.each(obj, function(index) {
            alert(obj[index].sendidjbuser);
            alert(obj[index].message);
        });


      }

You can add Jackson to your classpath or add dependencies to maven and Spring Mvc convert your list to json. 您可以将Jackson添加到您的类路径中,或将依赖项添加到maven中,Spring Mvc会将您的列表转换为json。 You only need add parameter to @RequestMapping produces="application/json", in your case it look @RequestMapping(value="getMessages", method=RequestMethod.GET, produces="application/json"), also parameter produces unnecessary but recommended. 您只需要向@ RequestMappingproduces =“ application / json”添加参数,在您的情况下,它看起来就是@RequestMapping(value =“ getMessages”,method = RequestMethod.GET,produces =“ application / json”),参数也会产生不必要的但推荐的。 And you not need any edit in your controller. 而且您不需要在控制器中进行任何编辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用jQuery和Ajax将动态对象列表发送到MVC中的控制器 - How to send a dynamic list of objects to controller in MVC using jQuery and Ajax 如何使用ajax和json将对象列表从spring mvc传递到jquery? - How to pass list of objects from spring mvc to jquery using ajax and json? 如何从mvc控制器获取列表以使用jquery ajax进行查看 - How to get a list from mvc controller to view using jquery ajax 如何获得 <list> 从MVC控制器使用jquery ajax查看 - How to get a <list> from mvc controller to view using jquery ajax 使用 Jquery Z3EB7106C3477A590E6BBF5DBFDE 在 Spring MVC controller 中传递字符串列表 - Passing a list of strings in a Spring MVC controller using Jquery Ajax 使用JQUERY AJAX(Spring MVC)从控制器中删除 - Delete from controller using JQUERY AJAX (Spring MVC) 如何使用 Ajax 调用将列表传递给 Spring MVC 控制器 - How to Pass List using Ajax call to Spring MVC Controller 使用Spring MVC和Ajax处理对象列表 - using Spring MVC and ajax to handle list of objects 如何将列表从Spring Controller传递到jQuery中的Ajax - How to pass a list from spring controller to ajax in jquery Spring MVC @ResponseBody,JSON,JSP。 试图返回列表 <Objects> 从Controller到JSP - Spring MVC @ResponseBody , JSON, JSP. Trying to Return List<Objects> from Controller to JSP
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM