【问题标题】:JQuery $.ajax by sending POST receiving 400 Bad requestJQuery $.ajax 通过发送 POST 接收 400 Bad request
【发布时间】:2014-09-20 13:16:35
【问题描述】:

在 jquery ajax 发布到 MVC 控制器时不断收到 400(错误请求)。我试图发送简单的数据,数组,有和没有 JSON.stringify ......我没有想法。 还能是什么?

Ajax 发送

$.ajax({
    type: 'POST',
    url: '../../taskaction/send',
    data: JSON.stringify({idTaskAction: 2, actioname: 3}),
    success: function (data, textStatus, jqXHR) {
      console.log('@Success sending action status: ' + textStatus);
    },
    error: function(jqXHR, textStatus, errorThrown){
      console.log('@Error sending action status: ' + textStatus);
    },
    contentType: "application/json; charset=utf-8",
    dataType: "json"
});

弹簧控制器

@RequestMapping(value = "/taskaction/send", 
        method = RequestMethod.POST, 
        produces = "application/json")
@ResponseBody
public Map<String, Object> sendAction(Principal principal,
        @RequestBody Map<String, Object> data, @PathVariable Long id) {
    logger.info("Task controller /taskaction/send ...");

  String actionname = (String) data.get("actionname");

  System.out.println("*****>>>>>>" + actionname );

  Map<String, Object> rdata = new HashMap<String, Object>();

  TaskAction action = null;

  rdata.put("success", true);

  return rdata;
}

来自检查员的 HTTP 请求

Remote Address:127.0.0.1:8080
Request URL:http://localhost:8080/myTasks/taskaction/send
Request Method:POST
Status Code:400 Petición incorrecta
Request Headersview source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip,deflate
Accept-Language:es-ES,es;q=0.8,en;q=0.6
Connection:keep-alive
Content-Length:33
Content-Type:application/json; charset=UTF-8
Cookie:JSESSIONID=9073BF5FA653C2C673AD9BCB787732C3
Host:localhost:8080
Origin:http://localhost:8080
Referer:http://localhost:8080/myTasks/task/upd/8
User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36
X-Requested-With:XMLHttpRequest
Request Payloadview source
{idTaskAction:2, actionname:3}
actionname: 3
idTaskAction: 2
Response Headersview source
Connection:close
Content-Language:es
Content-Length:990
Content-Type:text/html;charset=utf-8
Date:Sat, 20 Sep 2014 13:19:31 GMT
Server:Apache-Coyote/1.1

【问题讨论】:

    标签: jquery ajax json spring jakarta-ee


    【解决方案1】:

    我会说这是因为您的处理程序方法需要一个名为 id 的 @PathVariable,它可以转换为 Long,但是在您的 POST 请求中,您没有发送该参数,而在您的 @RequestMapping 中,您没有为 id 定义了一个 URI 模板变量。

    以下内容包含 id 作为 URI 模板变量,只要您传递的值可以转换为 Long,则请求应由您的请求处理程序方法处理。

    @RequestMapping(value = "/taskaction/send/{id}", method = RequestMethod.POST, produces = "application/json")
    

    我不能评论的唯一其他事情(并且可能会得到负面的 cmets)是使用 Map 作为@RequestBody。根据我的经验,使用定义了字段的具体对象类型效果更好。我认为你真正的问题是你的@RequestMapping 和@PathVariable。

    【讨论】:

    • 非常感谢,我找错地方了!我正在检查发送到服务器的 json 数据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 2016-05-18
    • 2019-11-18
    相关资源
    最近更新 更多