如何从 Spring MVC 控制器返回一个对象以响应 AJAX 请求? [英] How to return an object from a Spring MVC controller in response to AJAX request?

查看:22
本文介绍了如何从 Spring MVC 控制器返回一个对象以响应 AJAX 请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我的控制器:

@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代码:

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


提前致谢.

推荐答案

我需要这个 ajax 员工列表

I need this list of employee in ajax

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

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

地点:

  • @ResponseBody :将通知 spring 尝试转换其返回值并将其自动写入 http 响应.
  • @RequestBody :将通知 spring 尝试将传入请求正文的内容即时转换为您的参数对象.
  • @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.

在您的情况下,您需要 JSON 类型,您必须将 @ResponseBody 添加到您的方法签名或方法上方,并生成和使用可选的,例如:

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

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

在 AJAX 调用中使用:

and in AJAX call use:

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

在您的情况下 contentType: 'application/json' 不需要,默认为 'application/x-www-form-urlencoded;charset=UTF-8' 就够了.

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

并且您可以收到 AJAX 成功中的员工列表,对其进行迭代,如下所示:

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

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


注意: Jackson 映射器或任何其他映射器应该可用在构建路径上以进行 JSON 序列化和反序列化.


Note: Jackson mapper or any other mapper should be available on buildpath in order to work JSON serialize and deserialize.

另见:

这篇关于如何从 Spring MVC 控制器返回一个对象以响应 AJAX 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆