【问题标题】:ajax post to spring mvc appends "=" sign to request dataajax post到spring mvc附加“=”符号来请求数据
【发布时间】:2014-03-28 19:07:06
【问题描述】:

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

我的控制器代码是

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

在服务器端,它打印带有“=”符号的标记值,而在萤火虫控制台上,当我输入时打印值。

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

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

提前致谢, 问候。

【问题讨论】:

  • 您正在发送 dataType 'text' 并使用 application/json。您可能希望将您的 java 更改为使用 text/plain 或等价物。
  • Geoff 说得有道理。您正在打印请求而不是标签。
  • 你的handler方法完全矛盾。

标签: javascript jquery ajax spring-mvc


【解决方案1】:

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

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

如果您好奇,可以在ServletServerHttpRequest#getBodyFromServletRequestParameters(..) 中完成。

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

【讨论】:

  • 即使在删除 dataType 或将其更改为 text/plain 后仍然得到 =。
  • @geneb。在浏览器上打开网络工具并检查正在发送的内容。如果它仍然是 application/x-www-form-urlencoded 内容类型,你可能错过了一些东西。
  • 是的,你是对的。谢谢。必须在 Ajax JS 方面做 contentType -- 我正在更改 dataType
【解决方案2】:

仅供参考,根据 Sotirios 的回答,以下在 Ajax jQuery 代码中有效。

     $.ajax({
            type : "post",
            dataType : 'json', 
            contentType : 'text/plain', // This was added to delete the =
            url : 'myURL',  
            data : id
     })

【讨论】:

    猜你喜欢
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-24
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    相关资源
    最近更新 更多