如何通过JSON对象从阿贾克斯到Spring MVC的控制器? [英] How to pass Json object from ajax to spring mvc controller?
本文介绍了如何通过JSON对象从阿贾克斯到Spring MVC的控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的工作用SpringMVC上,我将数据从阿贾克斯到控制器,但我得到空值在我的控制器请检查以下
我的code 函数searchText()
{
VAR送出数据= {
PNAME:巴努•
LNAME:普拉萨德
}
$阿贾克斯({
键入:POST,
网址:/gDirecotry/ajax/searchUserProfiles.htm,
异步:真正的,
数据:送出数据,
成功:函数(结果)
{
}
}
myController的code
RequestMapping(值=/ gDirecotry / AJAX / searchUserProfiles.htm,方法= RequestMethod.POST)
公共@ResponseBody字符串getSearchUserProfiles(HttpServletRequest的要求)
{
字符串PNAME =的request.getParameter(PNAME);
//这里我得到空值
}
任何一个可以帮助我
解决方案
嘿享受以下$ C $ C。
的Javascript AJAX调用
函数searchText(){
VAR搜索= {
PNAME:巴努•
LNAME:普拉萨德
}
$阿贾克斯({
键入:POST,
的contentType:应用/ JSON的;字符集= UTF-8,
数据类型:JSON,
网址:/gDirecotry/ajax/searchUserProfiles.htm
数据:JSON.stringify(搜索),//注意重要的是
成功:函数(结果){
//做任何你想要的数据
}
});
}
春季控制器code
<$p$p><$c$c>RequestMapping(value="/gDirecotry/ajax/searchUserProfiles.htm",method=RequestMethod.POST) 公共@ResponseBody字符串getSearchUserProfiles(@RequestBody搜寻搜寻,HttpServletRequest的请求){ 字符串PNAME = search.getPName(); 字符串LNAME = search.getLName(); //你的逻辑下一个 }
以下搜索类将是如下:的
类搜索{
私人字符串PNAME;
私人字符串LNAME;
// getter和setter方法上述变量
}
利用这个阶级的是,在未来,你可以根据需要添加更多的变量,这个类。
例如:如果你想实现某种功能。
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
}
any one help me
解决方案
Hey enjoy the following code.
Javascript AJAX call
function searchText() {
var search = {
"pName" : "bhanu",
"lName" :"prasad"
}
$.ajax({
type: "POST",
contentType : 'application/json; charset=utf-8',
dataType : 'json',
url: "/gDirecotry/ajax/searchUserProfiles.htm",
data: JSON.stringify(search), // Note it is important
success :function(result) {
// do what ever you want with data
}
});
}
Spring controller code
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
}
Following Search class will be as follows
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对象从阿贾克斯到Spring MVC的控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文