sac*_*024 44 ajax jquery post http-status-code-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);
}
});
Run Code Online (Sandbox Code Playgroud)
它说:无法根据请求构建资源.我错过了什么?
sac*_*024 92
最后,我弄错了,原因是我需要对我发送的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"
});
Run Code Online (Sandbox Code Playgroud)
可能会帮助别人.
Nor*_*son 11
万一其他人遇到这种情况。我的网站在桌面浏览器上运行良好,但在 Android 设备上却收到 400 错误。
原来是防伪令牌。
$.ajax({
url: "/Cart/AddProduct/",
data: {
__RequestVerificationToken: $("[name='__RequestVerificationToken']").val(),
productId: $(this).data("productcode")
},
Run Code Online (Sandbox Code Playgroud)
问题是 .Net 控制器设置不正确。
我需要将属性添加到控制器:
[AllowAnonymous]
[IgnoreAntiforgeryToken]
[DisableCors]
[HttpPost]
public async Task<JsonResult> AddProduct(int productId)
{
Run Code Online (Sandbox Code Playgroud)
该代码需要审查,但现在至少我知道是什么原因造成的。400错误根本没有帮助。
是的。你需要stringify
的JSON
orlse数据400 bad request
,因为它不能识别数据发生错误。
400 Bad Request
Run Code Online (Sandbox Code Playgroud)
错误的请求。您的浏览器发送了此服务器无法理解的请求。
另外,您还需要添加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"
});
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您可以轻松修改所需的数据。它不会让您感到困惑,因为它是在 ajax 块之外定义的。
归档时间: |
|
查看次数: |
147428 次 |
最近记录: |