Spring Controller Ajax返回String

前端之家收集整理的这篇文章主要介绍了Spring Controller Ajax返回String前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我想将Spring MVC Controller中的String返回给Ajax.
它没有按预期工作并给出错误.

我的Ajax代码

function ajaxRequest(item) {

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

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

}

我的控制器:

@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控制台结果:

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

我在这里失踪了什么?

最佳答案
当您从使用@ResponseBody注释的处理程序方法返回String时,Spring将使用StringHttpMessageConverter将返回内容类型设置为text / plain.但是,您的请求没有该内容类型的Accept标头,因此Server(您的Spring应用程序)认为返回text / plain是不可接受的.

更改您的ajax以添加text / plain的Accept标头.

原文链接:https://www.f2er.com/spring/432538.html

猜你在找的Spring相关文章