如何将此列表值从控制器返回给ajax调用并成功打印?

问题描述 投票:0回答:1

这是我从rest控制器打印出列表值时得到的对象的模式。

[
   {
    "name": "Jon",
    "isUser": true
   },
   {
    "name": "Ween",
    "isUser": false
   }

]

但是问题是我不知道如何将这个值传递给我的ajax调用。我需要该值以进行进一步的工作。但是,每当我调用此控制器时,我的ajax返回error 500。这是我的休息控制器:

    @RequestMapping(value = "/getusers",  method = RequestMethod.GET)
    public List userShow(HttpServletRequest request, Model model) {

        List userlist = new ArrayList();
        try{
            userlist = JSONArray.fromObject(userService.getUserList());
            System.out.println(userlist);
        }catch (Exception e){
            logger.error(e);
        }
        return  userlist;
    }

我可以清楚地从userList中看到已打印的system.out的列表,但是我不确定为什么这些值不在ajax call中。也许我必须更改函数的return,我已经给定了list,因为我希望我的数据成为问题的第一部分中给出的数据。和我的ajax调用:

    $.ajax({
          type: "GET",
          url: "/getusers",
          success: function (response) {
           console.log(response);
           if(response === true) {
                  user = true;
             }
             else{
                 user = false;
              errorShow = "error getting values";
          }
      },
      async: false
  });

当该URL被点击时,值在controller中可见,但在console.log中我看到

获取http://localhost:3000/getusers 500

错误。如何在响应部分中获得这些值?

javascript java ajax spring spring-boot
1个回答
0
投票

如果您确实要返回列表,则可以像下面这样使用ResponseEntity:

@RequestMapping(value = "/getusers", method = RequestMethod.GET)
public ResponseEntity < List > userShow(HttpServletRequest request, Model model) {

    List userlist = new ArrayList();
    try {
        userlist = userService.getUserList();
        System.out.println(a);
    } catch (Exception e) {
        logger.error(e);
    }

    URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/").buildAndExpand("").toUri();
    return ResponseEntity.created(uri).body(userlist);
}

注意,由于JSONArray.fromObject()将为您将列表转换为JSON,因此我摆脱了ResposneEntity。>

© www.soinside.com 2019 - 2024. All rights reserved.