7

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?

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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");
    }

Comments

-2

Be sure that you have Jackson dependency. Spring MVC can relies on it.

1 Comment

Jackson is not involved here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.