Gor*_*akh 9 ajax jquery spring controller list
我必须将员工列表从Controller返回到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;
}
Run Code Online (Sandbox Code Playgroud)
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");
}
});
});
Run Code Online (Sandbox Code Playgroud)
});
提前致谢.
Abh*_*yak 16
我需要ajax中的员工列表
在春天,您需要对象序列化,反序列化和消息转换.在这种情况下,您需要使用@RequestBody和注释控制器处理程序方法@ResponseBody.
哪里:
在您的情况下,您需要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;
}
Run Code Online (Sandbox Code Playgroud)
并在AJAX调用中使用:
contentType: 'application/json'attribute告诉您要发送的数据类型.和dataType: json 属性告诉jquery将接收哪种内容类型的响应.在你的情况下contentType: 'application/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
});
},
Run Code Online (Sandbox Code Playgroud)
也可以看看:
| 归档时间: |
|
| 查看次数: |
51095 次 |
| 最近记录: |