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?
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
.
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With