Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
452 views
in Technique[技术] by (71.8m points)

How to pass Json object from ajax to spring mvc controller?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.html",
       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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...