难以将数据从 ajax 发送到 spring mvc 控制器
Having difficulties sending data from ajax to spring mvc controller
我的 ajax 代码如下所示:
function GetProjectlist() {
alert(department);
var obj = { department : department};
$.ajax({
type: "POST",
url: "http://localhost:8080/MyApplication/getAllProjects",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnGetProjectSuccess,
error: OnGetProjectError
});
}
另一方面,我的控制器看起来像这样:
@RequestMapping(value = "/getAllProjects", method = RequestMethod.POST,headers = {"Content-type=application/json"})
public @ResponseBody JsonJtableProjectListResponse getAllProjects(@RequestParam(value = "department", required = false) String department) {
System.out.print("department"+department);
logger.info("Home Controller -getAllProjects");
................................................ .....
当我在控制器中打印部门时,它是空的。谁能告诉我如何将部门从 ajax 传递给控制器?
尝试使用@RequestBody 注释而不是@RequestParam 注释,因为您正在发送json 数据。查看这篇文章了解如何操作。
对于简单的参数传递,使用类似下面的内容并像之前一样在服务器端使用@RequestParam。
$.ajax({
type: "GET",
url: "http://localhost:8080/MyApplication/getAllProjects",
data: {department:department},
dataType: "json",
success: OnGetProjectSuccess,
error: OnGetProjectError
});
我的 ajax 代码如下所示:
function GetProjectlist() {
alert(department);
var obj = { department : department};
$.ajax({
type: "POST",
url: "http://localhost:8080/MyApplication/getAllProjects",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnGetProjectSuccess,
error: OnGetProjectError
});
}
另一方面,我的控制器看起来像这样:
@RequestMapping(value = "/getAllProjects", method = RequestMethod.POST,headers = {"Content-type=application/json"})
public @ResponseBody JsonJtableProjectListResponse getAllProjects(@RequestParam(value = "department", required = false) String department) {
System.out.print("department"+department);
logger.info("Home Controller -getAllProjects");
................................................ .....
当我在控制器中打印部门时,它是空的。谁能告诉我如何将部门从 ajax 传递给控制器?
尝试使用@RequestBody 注释而不是@RequestParam 注释,因为您正在发送json 数据。查看这篇文章了解如何操作。
对于简单的参数传递,使用类似下面的内容并像之前一样在服务器端使用@RequestParam。
$.ajax({
type: "GET",
url: "http://localhost:8080/MyApplication/getAllProjects",
data: {department:department},
dataType: "json",
success: OnGetProjectSuccess,
error: OnGetProjectError
});