【发布时间】:2022-06-14 23:53:56
【问题描述】:
我正在做一个项目,我们尝试通过 AJAX 在 UI 和 RestAPI 之间交换不同的参数。 RestAPI 定义了数据的外观:
我试图用这种方式解决它:
$(document).ready(function(){
$("#submit").click(function(){
var credentials = [
{user_name: $("#uname").val(),
password: $("#pwd").val()
}
];
alert(credentials);
$.ajax({
url:"../rest/user/login",
type:"POST",
data:JSON.stringify({credentials: credentials}),
success: function(){
window.location.href = "startrackhome.html";
},
error: function error(response){
try{
var json = JSON.parse(response.responseText);
if(typeof json.message === 'undefined'){
throw new Error("Response json has no message");
}
else{
alert(json.message);
}
}
catch(ex){
alert("unexpected error (code:" + response.status +")");
}
}
});
});
});
警报显示:[object Object]
而且我总是收到一条错误消息(错误:400),这意味着我一定犯了一个错误,我认为我发送的格式是错误的,但我不知道如何修复它。
我希望你能帮助我! :)
【问题讨论】:
-
我认为你不应该将 json 字符串化,而是将对象按原样传递给 $.ajax,并添加
contentType: "application/json" -
我试过了,但我仍然收到错误消息,所以这不是我猜的解决方案
-
你的服务器支持 json 请求吗?如果不尝试
contentType: "application/x-www-form-urlencoded",请尝试data: {credentials: JSON.stringify(credentials)} -
据我所知,服务器支持 json 请求(我们将其用于另一个请求)。但我仍然尝试了你的选择,它也没有工作
-
您有错误信息吗?因为那个请求很好,它可能是别的东西,你确定凭证是有效的吗?
标签: ajax post http-status-code-400 postdata