小编典典

在jQuery Ajax POST中获取400错误的请求错误

ajax

我正在尝试使用Jquery发送Ajax POST请求,但是我遇到了400错误的请求错误。

这是我的代码:

$.ajax({
  type: 'POST',
  url: "http://localhost:8080/project/server/rest/subjects",
  data: {
    "subject:title":"Test Name",
    "subject:description":"Creating test subject to check POST method API",
    "sub:tags": ["facebook:work", "facebook:likes"],
    "sampleSize" : 10,
    "values": ["science", "machine-learning"]
  },
  error: function(e) {
    console.log(e);
  }
});

它说:无法根据请求构建资源。我想念什么?


阅读 578

收藏
2020-07-26

共1个答案

小编典典

最后,我弄错了,原因是我需要对发送的JSON数据进行字符串化处理。我必须在XHR对象中设置内容类型和数据类型。所以正确的版本在这里:

$.ajax({
  type: 'POST',
  url: "http://localhost:8080/project/server/rest/subjects",
  data: JSON.stringify({
    "subject:title":"Test Name",
    "subject:description":"Creating test subject to check POST method API",
    "sub:tags": ["facebook:work", "facebook:likes"],
    "sampleSize" : 10,
    "values": ["science", "machine-learning"]
  }),
  error: function(e) {
    console.log(e);
  },
  dataType: "json",
  contentType: "application/json"
});

可能会帮助别人。

2020-07-26