2013-12-18 40 views
6

我想從Spring MVC Controller返回字符串到Ajax。 它不按預期工作,並提供錯誤。Spring Controller + 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] 

缺少什麼我在這裏

這個我的Ajax代碼?

回答

-1

確保您擁有傑克遜依賴。 Spring MVC可以依靠它。

+0

傑克遜沒有捲入這裏。 –

4

我已經解決了。我們可以用迴應作者返回正確的值。

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

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

    ... 

    response.getWriter().println(myItem + "bla bla bla"); 
    } 
5

當你從@ResponseBody註釋處理程序方法返回一個String,Spring將使用一個StringHttpMessageConverter其設置返回內容類型text/plain。但是,您的請求沒有針對該內容類型的Accept標頭,因此服務器(您的Spring應用程序)認爲返回text/plain是不可接受的。

更改您的ajax,爲text/plain添加Accept標頭。