AJAX-Spring MVC中不支持的媒体类型错误

时间:2014-01-22 09:36:19

标签: java jquery ajax spring spring-mvc

我正在尝试将字符串传递给Ajax Stringify的控制器使用,但是我收到了这个错误 415(不支持的媒体类型) 我的Ajax电话:

$.ajax({
     type: "POST",
     contentType : 'application/json; charset=utf-8',
     dataType : 'json',
     url: "addSample",
     data: JSON.stringify(search), // Note it is important
     cache : false,
     beforeSend : function(xhr) {
        xhr.setRequestHeader("Accept", "application/json");
        xhr.setRequestHeader("Content-Type", "application/json");
     },
     success : function(response) {
         console.log("Success: "+ response);            
     },
     error : function(xhr) {
         console.log("Sorry, there was a problem! " + xhr.responseText);
     },
     complete : function() {
         console.log("Request complete");
     }
});

传递字符串:

var search = {
     " name" : "aa",
      "sname": "bb",
      "dname" : "cc"
}

我的弹簧控制器功能:

@RequestMapping(headers={"Accept=application/json"},value = "addSample", method = RequestMethod.POST)
    public @ResponseBody
    String addData(HttpServletRequest request,@RequestBody final DemoDTO demoDTO)
    {
        return  "{\"value\":\"true\"}";
    }

我的DTO:

public class DemoDTO implements Serializable{
    private String name;
    private String sname;
    private String dname;
  //getter setter
}

请帮我解决这个问题....

1 个答案:

答案 0 :(得分:0)

尝试替换它:

beforeSend : function(xhr) {
    xhr.setRequestHeader("Accept", "application/json");
    xhr.setRequestHeader("Content-Type", "application/json");
 },

有了这个:

headers: { 
    'Accept': 'application/json',
    'Content-Type': 'application/json' 
},

此外,从spring控制器中删除headers={"Accept=application/json"},如下所示:

@RequestMapping(value = "addSample", method = RequestMethod.POST)
public @ResponseBody
String addData(HttpServletRequest request,@RequestBody DemoDTO demoDTO)
{
    return  "{\"value\":\"true\"}";
}