gpt4 book ai didi

javascript - ajax post to spring mvc 附加 "="标志来请求数据

转载 作者:数据小太阳 更新时间:2023-10-29 06:11:43 24 4
gpt4 key购买 nike

我正在尝试通过 ajax 将数据发布到 spring Controller 。我的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));
}
});
}

我的 Controller 代码是

@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);
}

在服务器端它打印附加有“=”符号的标签的值,而在 firebug 控制台上打印我输入的值。

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

谁能告诉我这里有什么问题。

提前致谢,问候。

最佳答案

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

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

如果你很好奇,这是在 ServletServerHttpRequest#getBodyFromServletRequestParameters(..) 中完成的.

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

关于javascript - ajax post to spring mvc 附加 "="标志来请求数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22033180/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com