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

前端 未结 5 1265
小蘑菇
小蘑菇 2020-12-01 04:48

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()
{         


        
5条回答
  •  孤街浪徒
    2020-12-01 05:13

    Use this method if you dont want to make a class you can directly send JSON without Stringifying. Use Default Content Type. Just Use @RequestParam instead of @RequestBody. @RequestParam Name must be same as in 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
        }
        });
    

    Spring Controller

    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
       }
    

提交回复
热议问题