我正在使用SpringMVC,我将数据从ajax传递给控制器,但我的控制器中有空值,请检查下面的代码
function searchText()
{
var sendData = {
"pName" : "bhanu",
"lName" :"prasad"
}
$.ajax({
type: "POST",
url: "/gDirecotry/ajax/searchUserProfiles.htm,
async: true,
data:sendData,
success :function(result)
{
}
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
任何人帮助我
Vij*_*kar 45
嘿,喜欢以下代码.
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
}
});
}
Run Code Online (Sandbox Code Playgroud)
}
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
}
Run Code Online (Sandbox Code Playgroud)
以下Search类将如下
class Search {
private String pName;
private String lName;
// getter and setters for above variables
}
Run Code Online (Sandbox Code Playgroud)
此类的优点在于,将来您可以根据需要向此类添加更多变量.
例如.如果要实现排序功能.
如果你不想创建一个类,你可以使用这个方法,你可以直接发送没有字符串化的JSON.使用默认内容类型.只需使用@RequestParam而不是@RequestBody.
@RequestParam名称必须与中的相同json.
Ajax Call
function searchText() {
var search = {
"pName" : "bhanu",
"lName" :"prasad"
}
$.ajax({
type: "POST",
/*contentType : 'application/json; charset=utf-8',*/ //use Default contentType
dataType : 'json',
url: "/gDirecotry/ajax/searchUserProfiles.htm",
data: search, // Note it is important without stringifying
success :function(result) {
// do what ever you want with data
}
});
Run Code Online (Sandbox Code Playgroud)
弹簧控制器
RequestMapping(value="/gDirecotry/ajax/searchUserProfiles.htm",method=RequestMethod.POST)
public @ResponseBody String getSearchUserProfiles(@RequestParam String pName, @RequestParam String lName) {
String pNameParameter = pName;
String lNameParameter = lName;
// your logic next
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
80029 次 |
| 最近记录: |