Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get data from spring controller by ajax?

I have an ajax on a jsp page which calls a spring controller through URL /check .

$.ajax({
    type : "GET",
    url : "${pageContext.request.contextPath}/check",
    data : {
    "id" : ${articleCount}
    },
    success: function(data){
    //response from controller
    }
});

Now, the controller looks like,

@RequestMapping("/check")
public String check(@RequestParam Integer id, HttpServletRequest request,
        HttpServletResponse response, Model model) {
    boolean a = getSomeResult();
    if (a == true) {
        model.addAttribute("alreadySaved", true);
        return view;
    } else
        model.addAttribute("alreadySaved", false);

    return view;
}

I sent data using model and tried to access it in success: function(data) as "${alreadySaved}"but it shows blank.

Is there any way I can receive that true/false data on the view page?

like image 997
Sujan Avatar asked Nov 07 '14 05:11

Sujan


3 Answers

You have to add the @ResponseBody annotation for spring ajax calls example

@RequestMapping("/check")     
@ResponseBody
public String check(@RequestParam Integer id, HttpServletRequest request, HttpServletResponse response, Model model) {
    boolean a = getSomeResult();
    if (a == true) {
        model.addAttribute("alreadySaved", true);
        return view;
    } else {
        model.addAttribute("alreadySaved", false);
        return view;
    }
}
like image 177
Madhesh Avatar answered Sep 27 '22 15:09

Madhesh


use @ResponseBody

Spring will bind the return value to outgoing HTTP response body when you add @ResponseBody annotation.

@ResponseBody
public String check(@RequestParam Integer id, HttpServletRequest request, HttpServletResponse response, Model model) {
    boolean a = getSomeResult();
    if (a == true) {
        return "already saved";
    } 
    return "error exist";
}

Spring will use HTTP Message converters to convert the return value to HTTP response body [serialize the object to response body], based on Content-Type used in request HTTP header.

for more info:

http://websystique.com/springmvc/spring-mvc-requestbody-responsebody-example/

like image 25
Dulith De Costa Avatar answered Sep 27 '22 15:09

Dulith De Costa


Controller part

You have to add the @ResponseBody annotation for spring ajax calls example

View Part

$.ajax({
    type : "GET",
    url : "${pageContext.request.contextPath}/check",
    data : {
        "id" : ${articleCount}
    },
    success: function(data){
        $('#input_field').val(data);
    }
});
like image 23
tofindabhishek Avatar answered Sep 27 '22 17:09

tofindabhishek