jQuery 如何从 Spring MVC 控制器返回一个对象以响应 AJAX 请求?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23267113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 02:13:49  来源:igfitidea点击:

How to return an object from a Spring MVC controller in response to AJAX request?

jqueryajaxspringlistcontroller

提问by Gorakh

I have to return a list of employees from a controller in response to jQuery AJAX request. How should I do for it?

我必须从控制器返回员工列表以响应 jQuery AJAX 请求。我该怎么办?

My controller:

我的控制器:

@RequestMapping("phcheck")
public ModelAndView pay(@RequestParam("empid") int empid, String fdate, String tdate) {
    ModelAndView mav = new ModelAndView("phcheck");
    List<Employee> employees = entityManager.createQuery(
        "SELECT e FROM Employee e WHERE e.empId = " + empid, Employee.class)
        .getResultList();
    mav.addObject("employees", employees); // I need this list of employee in AJAX

    return mav;
}


AJAX code in the related view:


相关视图中的 AJAX 代码:

$(document).ready(function () {
    $("#empid").change(function () {
        if ($("#fdate").val() != "" && $("#tdate").val() != "" && $("#empid").val() != "") {
            jQuery.ajax({
                url: "phcheck.htm?empid=" + $("#empid").val() +
                                 "&&fdate=" + $("#fdate").val() +
                                 "&&tdate=" + $("#tdate").val(),
                success: function (data) {
                    alert(data + "success");
                },
                error: function (data) {
                    alert(data + "error");
                }
            });
        } else {
            alert("Please fill the from date and to date or select the employee id");
            $("#empid .option").attr("selected", "selected");
        }
    });
});


Thanks in advance.


提前致谢。

回答by Abhishek Nayak

I need this list of employee in ajax

我需要这份 ajax 员工名单

In spring when you need object serialization, de-serialization and message conversion. in that case you need to annotate your controller handler method with @RequestBodyand @ResponseBody.

在 spring 需要对象序列化、反序列化和消息转换时。在这种情况下,您需要使用@RequestBody和注释控制器处理程序方法@ResponseBody

Where:

在哪里:

  • @ResponseBody: will inform spring that try to convert its return value and write it to the http response automatically.
  • @RequestBody: will inform spring that try to convert the content of the incoming request body to your parameter object on the fly.
  • @ResponseBody:将通知 spring 尝试转换其返回值并将其自动写入 http 响应。
  • @RequestBody:将通知 spring 尝试将传入请求正文的内容动态转换为您的参数对象。

in your case you need JSON type, you have to add @ResponseBodyto your method signature or just above the method, and produces and consumes which are optional, like:

在您的情况下,您需要 JSON 类型,您必须添加@ResponseBody到您的方法签名或刚好在方法上方,并且生产和消费是可选的,例如:

@RequestMapping(value="phcheck", method=RequestMethod.GET
                produces="application/json")
public @ResponseBody List<Employee> pay(@RequestParam("empid") int empid, String fdate, String tdate) {

  //get your employee list here
  return empList;
}

and in AJAX call use:

并在 AJAX 调用中使用:

  • contentType: 'application/json'attribute tells the type of data you're sending. and
  • dataType: jsonattribute tells jquery what content type of response will receive.
  • contentType: 'application/json'属性告诉您发送的数据类型。和
  • dataType: json属性告诉 jquery 将收到什么内容类型的响应。

in your case contentType: 'application/json'is not needed, default one i.e. 'application/x-www-form-urlencoded; charset=UTF-8'is enough.

在你的情况下contentType: 'application/json'不需要,默认一个 ie'application/x-www-form-urlencoded; charset=UTF-8'就足够了。

and you can receive list of employees in your AJAX success, to iterate over it do like:

并且您可以在 AJAX 成功中接收员工列表,对其进行迭代,例如:

  success: function (data) {
          $.each(data, function(index, currEmp) {
             console.log(currEmp.name); //to print name of employee
         });    
        },



Note:笔记:Hymanson mapperHyman逊映射器或任何其他映射器应该在构建路径上可用,以便进行 JSON 序列化和反序列化。

See Also:

也可以看看:

回答by geoand

@RequestMapping(value = "phcheck", produces = "application/json")
@ResponseBody
public ModelAndView pay(@RequestParam("empid") int empid, @RequestParam("fdate") String fdate, @RequestParam("tdate") String tdate) {

   return entityManager.createQuery("select e from Employee e where e.empId="+empid, Employee.class).getResultList();
}


url:"phcheck.htm?empid="+$("#empid").val()+"&fdate="+$("#fdate").val()+"&tdate="+$("#tdate").val()

In Spring MVC you will have to have registered MappingHymanson2HttpMessageConverter like being done here

在 Spring MVC 中,您必须像在这里完成一样注册 MappingHymanson2HttpMessageConverter

回答by DavidA

The ModelAndView implies you plan to render a view, which you don't. To just return the object, use the @ResponseBody annotation:

ModelAndView 暗示您计划渲染视图,而您不打算渲染视图。要仅返回对象,请使用 @ResponseBody 注释:

@RequestMapping("phcheck")
public @ResponseBody List<Employee> pay(@RequestParam("empid") int empid, String fdate, String tdate) {
   return entityManager.createQuery("select e from Employee e where e.empId="+empid, Employee.class).getResultList();
}

Also, you should be more careful about how you handle queries. Your query is insecure and would allow sql injection. For example, if someone called your method with empId = "'15' or '1'='1'", then it would return the entire list of employees.

此外,您应该更加小心处理查询的方式。您的查询不安全,将允许 sql 注入。例如,如果有人使用 empId = "'15' 或 '1'='1'" 调用您的方法,那么它将返回整个员工列表。

回答by cse

Make the method as @ResponseBody Type in the controller and in the ajax take the List from success function.

在控制器中将该方法设为 @ResponseBody Type,并在 ajax 中从成功函数中获取 List。

Put the Hymanson Mapper file in Pom.xml file if using Maven

如果使用 Maven,请将 Hymanson Mapper 文件放在 Pom.xml 文件中