且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过JSON对象从阿贾克斯到Spring MVC的控制器?

更新时间:2023-02-25 16:42:18

嘿享受以下$​​ C $ C。

的Javascript AJAX调用

 函数searchText(){
   VAR搜索= {
      PNAME:巴努•
      LNAME:普拉萨德
   }
   $阿贾克斯({
      键入:POST,
      的contentType:应用/ JSON的;字符集= UTF-8,
      数据类型:JSON,
      网址:/gDirecotry/ajax/searchUserProfiles.htm
      数据:JSON.stringify(搜索),//注意重要的是
      成功:函数(结果){
       //做任何你想要的数据
     }
  });
 

}

春季控制器code

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.