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

查看:172
本文介绍了如何从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;
}


相关 view 中的AJAX代码:


AJAX code in the related view:

$(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.

推荐答案

我需要使用ajax的员工列表

I need this list of employee in ajax

在春季,当您需要对象序列化,反序列化和消息转换时.在这种情况下,您需要使用@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映射器或任何其他映射器都应可用在buildpath上,以便进行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天全站免登陆