在jQuery Ajax POST中获取400错误的请求错误
我正在尝试使用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个解决方案
90 votes
最后,我弄错了,原因是我需要对发送的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"
});
可能会帮助别人。
sachinjain024 answered 2020-07-25T15:42:50Z
2 votes
是。 您需要content type datatype数据,否则会出现415错误,因为它无法识别数据。
400 Bad Request
错误的请求。 您的浏览器发送了一个请求,要求该服务器无法 理解。
另外,您还需要添加content type和datatype。 如果不是这样,您将遇到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块之外定义,因此不会使您感到困惑。
Dulith De Costa answered 2020-07-25T15:43:32Z
1 votes
这个问题有点老了……但是如果有人遇到错误400,它也可能是由于需要将csrfToken作为发布请求的参数发布。
您必须在模板中通过手工艺获得名称和价值:
window.csrfTokenName = "{{ craft.config.csrfTokenName|e('js') }}";
window.csrfTokenValue = "{{ craft.request.csrfToken|e('js') }}";
并在您的请求中传递它们
data: window.csrfTokenName+"="+window.csrfTokenValue
Benoît Schiex answered 2020-07-25T15:44:00Z
0 votes
您需要使用以下功能从“数据”对象构建查询
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
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);
}
});
Christian Ezeani answered 2020-07-25T15:44:25Z