61

我正在尝试使用 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);
  }
});

它说:无法从请求中构建资源。我错过了什么?

4

5 回答 5

115

最后,我得到了错误,原因是我需要对发送的 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"
});

也许它会帮助别人。

于 2013-04-17T08:01:04.557 回答
7

是的。您需要数据或发生错误stringify,因为它无法识别数据。JSON400 bad request

400 Bad Request

错误的请求。您的浏览器发送了此服务器无法理解的请求。

另外,您还需要添加content typedatatype。如果不是,你会遇到415错误,上面写着Unsupported Media Type

415 不支持的媒体类型

尝试这个。

var newData =   {
                  "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"]
                  };

var dataJson = JSON.stringify(newData);

$.ajax({
  type: 'POST',
  url: "http://localhost:8080/project/server/rest/subjects",
  data: dataJson,
  error: function(e) {
    console.log(e);
  },
  dataType: "json",
  contentType: "application/json"
});

通过这种方式,您可以轻松修改所需的数据。它不会让您感到困惑,因为它是在 ajax 块之外定义的。

于 2018-05-17T08:05:13.700 回答
5

以防其他人遇到这种情况。我有一个在桌面浏览器上运行良好的网站,但我在使用 Android 设备时遇到了 400 个错误。

原来是防伪令牌。

$.ajax({
        url: "/Cart/AddProduct/",
        data: {
            __RequestVerificationToken: $("[name='__RequestVerificationToken']").val(),
            productId: $(this).data("productcode")
        },

问题是 .Net 控制器设置不正确。

我需要将属性添加到控制器:

    [AllowAnonymous]
    [IgnoreAntiforgeryToken]
    [DisableCors]
    [HttpPost]
    public async Task<JsonResult> AddProduct(int productId)
    {

代码需要审查,但现在至少我知道是什么原因造成的。400 错误根本没有帮助。

于 2020-03-30T13:52:44.937 回答
2

这个问题有点老了......但万一有人遇到错误400,它也可能来自需要将csrfToken作为参数发布到发布请求。

您必须在模板中从工艺中获取名称和价值:

<script type="text/javascript">
    window.csrfTokenName = "{{ craft.config.csrfTokenName|e('js') }}";
    window.csrfTokenValue = "{{ craft.request.csrfToken|e('js') }}";
</script>

并在您的请求中传递它们

data: window.csrfTokenName+"="+window.csrfTokenValue
于 2017-01-21T16:17:43.653 回答
0

您需要使用以下函数从“数据”对象构建查询

function buildQuery(obj) {
        var Result= '';
        if(typeof(obj)== 'object') {
            jQuery.each(obj, function(key, value) {
                Result+= (Result) ? '&' : '';
                if(typeof(value)== 'object' && value.length) {
                    for(var i=0; i<value.length; i++) {
                        Result+= [key+'[]', encodeURIComponent(value[i])].join('=');
                    }
                } else {
                    Result+= [key, encodeURIComponent(value)].join('=');
                }
            });
        }
        return Result;
    }

然后继续

var 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"]
}

$.ajax({
  type: 'POST',
  url: "http://localhost:8080/project/server/rest/subjects",
  data: buildQuery(data),
  error: function(e) {
    console.log(e);
  }
});
于 2013-04-15T14:05:22.477 回答