我必须从控制器返回员工列表以响应jQuery AJAX请求。我应该怎么做?
我的控制器:
@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"); } }); });
提前致谢。
I need this list of employee in ajax
在spring,当你需要对象序列化,反序列化和消息转换时。在这种情况下,你需要使用@RequestBody和注释控制器处理程序方法@ResponseBody。
@RequestBody
@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; }
在AJAX调用中使用:
contentType: 'application/json'
dataType: json
'application/x-www-form-urlencoded; charset=UTF-8'
并且你可以收到AJAX成功案例中的员工列表,以对其进行迭代:
success: function (data) { $.each(data, function(index, currEmp) { console.log(currEmp.name); //to print name of employee }); },
注意: Jackson映射器或任何其他映射器应该在buildpath上可用,以便进行JSON序列化和反序列化。