本文介绍了如何将 Json 对象从 ajax 传递到 spring mvc 控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在研究 SpringMVC,我正在将数据从 ajax 传递到控制器,但我的控制器中出现空值,请检查下面的代码
I am working on SpringMVC, I am passing data from ajax to controller but i got null value in my controller please check my code below
function searchText()
{
var sendData = {
"pName" : "bhanu",
"lName" :"prasad"
}
$.ajax({
type: "POST",
url: "/gDirecotry/ajax/searchUserProfiles.htm,
async: true,
data:sendData,
success :function(result)
{
}
}
MyControllerCode
RequestMapping(value="/gDirecotry/ajax/searchUserProfiles.htm",method=RequestMethod.POST)
public @ResponseBody String getSearchUserProfiles(HttpServletRequest request)
{
String pName = request.getParameter("pName");
//here I got null value
}
谁来帮帮我
推荐答案
嘿,享受下面的代码.
Javascript AJAX 调用
function searchText() {
var search = {
"pName" : "bhanu",
"lName" :"prasad"
}
$.ajax({
type: "POST",
contentType : 'application/json; charset=utf-8',
dataType : 'json',
url: "/gDirecotry/ajax/searchUserProfiles.html",
data: JSON.stringify(search), // Note it is important
success :function(result) {
// do what ever you want with data
}
});
}
Spring 控制器代码
RequestMapping(value="/gDirecotry/ajax/searchUserProfiles.htm",method=RequestMethod.POST)
public @ResponseBody String getSearchUserProfiles(@RequestBody Search search, HttpServletRequest request) {
String pName = search.getPName();
String lName = search.getLName();
// your logic next
}
以下搜索类将如下
class Search {
private String pName;
private String lName;
// getter and setters for above variables
}
这个类的优点是,以后你可以根据需要向这个类添加更多变量.
例如,如果您想实现排序功能.
Advantage of this class is that, in future you can add more variables to this class if needed.
Eg. if you want to implement sort functionality.
这篇关于如何将 Json 对象从 ajax 传递到 spring mvc 控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!