ajax post to spring mvc附加"="符号来请求数据

Sha*_*han 5 javascript ajax jquery spring-mvc

我试图通过ajax帖子将数据发布到spring控制器.我的ajax代码是

function postData(tag){
console.debug(tag);

var targetUrl = "/add/tag";
$.ajax({
    url : targetUrl,
    type : "POST",
    data : tag,
    dataType : "text",
    success : function(response){
        console.debug(response);
    },
    error : function(){
        console.debug("error : ".concat(response));
    }
});
}
Run Code Online (Sandbox Code Playgroud)

我的控制器代码是

@RequestMapping(value = "/add/tag", method = POST, consumes = { "application/json" },headers = "content-type=application/x-www-form-urlencoded")
@ResponseBody
public Integer addTag(HttpServletRequest request,
    @PathVariable("uid") String gatheringUid, @RequestBody String tag) {
    System.out.print(tag);
    return gatheringService.updateGathering(gatheringUid, tags);
}
Run Code Online (Sandbox Code Playgroud)

在服务器端,它打印附加"="符号的标签的值,而在firebug控制台上的值打印为我输入.

例如,当我发布数据"test"时,在firebug控制台上打印"test",在服务器端控制台上打印"test =".

任何人都可以告诉我这里有什么问题.

在此先感谢,问候.

Sot*_*lis 6

这是AJAX发送内容类型为的POST的结果application/x-www-form-urlencoded.

Spring使用a StringHttpMessageConverter来解析绑定到带@RequestBody注释的String参数的参数.在内部,这将检查请求是否为表单POST.如果是,它会将整个身体反序列化,就好像它是一个表单提交一样.在这种情况下,单个单词text看起来好像是,例如,<input>没有值的单个元素,即.text=.

如果你很好奇,那就完成了ServletServerHttpRequest#getBodyFromServletRequestParameters(..).

将您的内容类型更改为更合适的内容text/plain.不要用dataType.使用contentTypeheaders.