如何从控制器返回一个列表到Ajax调用并在成功时打印它?

huangapple go评论82阅读模式
英文:

How to return a List from controller to Ajax call and print it in the success?

问题

这是从我的 REST 控制器打印出的列表值的对象模式。

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

但问题是我不知道如何将这些值获取到我的 ajax 调用中。我需要这些值以便进行进一步的工作。但无论何时我调用这个控制器,我的 ajax 返回 500 错误

这是我的 REST 控制器:

@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;
}

我可以清楚地看到从 system.out 打印出的 userList 列表,但我不确定为什么这些值未传递到 ajax 调用中。也许我需要更改函数的 return,因为我想要的数据与我在问题的第一部分中提供的数据一致。

此外,这是我的 ajax 调用:

$.ajax({
      type: "GET",
      url: "/getusers",
      success: function (response) {
       console.log(response);
       if(response === true) {
              user = true;
         }
         else{
             user = false;
          errorShow = "获取值时出错";
      }
  },
  async: false
});

当这个 URL 被访问时,值可以在控制台中看到,但在 console.log 中,我看到了错误信息:

GET http://localhost:3000/getusers 500

请问如何在响应部分中获取这些值呢?

英文:

This is the pattern of the object I'm getting when I printed out my list value from rest controller.

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

]

but the problem is I dont know how can I get this value to my ajax call. I need that values for further work. But whenever I'm calling this controller my ajax return error 500.
this is my rest controller:

    @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;
    }

I can clearly see the list of the printed userList from system.out but i'm not sure why these values are not going in the ajax call. Maybe I've to change the return of my function , I've given list as I want my data as the provided data I have given in the first part of the question.
and
my ajax call :

    $.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
  });

when this url hits, values are seen in the controller but in the console.log i see

> GET http://localhost:3000/getusers 500

error. How can I get those values in the response section?

答案1

得分: 3

我认为你在类级别上使用了 @Controller 注解。
如果你使用 @RestController,就不需要显式地写 @ResponseBody。

另外,代替

@RequestMapping(value = " /getusers ", method = RequestMethod.GET)
你可以使用新的方法注解,像这样。
@GetMapping(" /getusers ")

英文:

I think you are using @Controller annotation at the class level.
If you use @RestController you will not have to write @Responsebody explicitly.

Also instead of
@RequestMapping(value = "/getusers", method = RequestMethod.GET)
you can use new method annotations like so.
@GetMapping("/getusers")

答案2

得分: 1

如果您真的想要返回List,您可以像这样使用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(),因为ResposneEntity会负责将List转换为JSON。此外,最好指定List的类型,例如:List<User>

英文:

If you really want to return the List you can use ResponseEntity like this:

@RequestMapping(value = &quot;/getusers&quot;, method = RequestMethod.GET)
public ResponseEntity &lt;List&gt; 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(&quot;/&quot;).buildAndExpand(&quot;&quot;).toUri();
    return ResponseEntity.created(uri).body(userlist);
}

Notice that I got rid of the JSONArray.fromObject() because ResposneEntity will take of converting the List into JSON for you.
Also it's preferred to specify the List type, for example: List&lt;User&gt;

答案3

得分: 1

只需在方法级别使用@ResponseBody注解,您就不必再将列表转换为数组。直接返回列表。

从:

JSONArray.fromObject(userService.getUserList())

改为:

userService.getUserList()
英文:

Just use @Responsebody annotation on method level and you don't have to convert list to array anymore. Return the list directly.

Change

JSONArray.fromObject(userService.getUserList())

To

userService.getUserList()

huangapple
  • 本文由 发表于 2020年6月6日 00:27:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/62220025.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定