Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Controller + Ajax return String

I want to return String from Spring MVC Controller to Ajax. It is not working as expected and gives error.

My Ajax codes for this:

function ajaxRequest(item) {

    $.ajax({
        type: "POST",
        url: "/myPage",
        data: {
           item: item
        },
        success: function (html) {

            alert(html);
        },
        error: function(e) {
            console.log("Error:" + e);
        }
    });

}

My Controller:

@RequestMapping(value = "/myPage", method= RequestMethod.POST, produces="text/plain")
public @ResponseBody String myController(HttpServletRequest request) {
String myItem = request.getParameter("item");   

...

return myItem + "bla bla bla";
}

Chrome console result:

POST http://localhost:8080/myPage 406 (Not Acceptable) jquery.js
Error:[object XMLHttpRequest] 

What am i missing here?

like image 530
AkiraYamaokaNC Avatar asked Dec 18 '13 09:12

AkiraYamaokaNC


2 Answers

When you return a String from a handler method annotated with @ResponseBody, Spring will use a StringHttpMessageConverter which sets the return content-type to text/plain. However, your request does not have an Accept header for that content-type so the Server (your Spring app) deems it unacceptable to return text/plain.

Change your ajax to add the Accept header for text/plain.

like image 55
Sotirios Delimanolis Avatar answered Oct 17 '22 23:10

Sotirios Delimanolis


I have solved it. We can return correct values with response writer.

    @RequestMapping(value = "/myPage")
    public void myController(HttpServletRequest request, HttpServletResponse response) throws IOException {

    String myItem = request.getParameter("item");   

    ...

    response.getWriter().println(myItem + "bla bla bla");
    }
like image 36
AkiraYamaokaNC Avatar answered Oct 17 '22 22:10

AkiraYamaokaNC