gpt4 book ai didi

javascript - JSON 的 Ajax 调用错误

转载 作者:行者123 更新时间:2023-11-28 18:57:49 24 4
gpt4 key购买 nike

我在下面进行 ajax 调用并收到一个我不明白的错误。 success 函数中的变量响应看起来像

{"status": "complete", "username": "test", "error": "0", "message": ""}

但是,当我在 success 函数中调用三个警报函数时,第一个函数打印出上面的值,但接下来的两个函数打印出 undefined。我知道错误键存在,但是 javascript 无法识别它。结果我的窗口崩溃了。

$.ajax({
url: '/index.php/api/userLogin',
data: userInfo,
datatype: 'json',
async: 'false',
type: 'POST',
success: function(response)
{
alert(response); //prints correct response
alert(response.error); //prints undefined
alert(response["error"]); //prints undefined
},
error: function(xhr, status, error)
{
var err = eval("(" + xhr.responseText + ")");
//alert("Please Try Again, we had an internal error!");
alert(err.message);
}
});

有人可以解释一下发生了什么以及如何解决这个问题吗?

最佳答案

这是由两个因素共同造成的:

  1. 服务器正在发送内容类型错误的 JSON
  2. 您使用了错误的大小写来覆盖它

因此,jQuery 将 JSON 解释为(可能)纯文本(这就是为什么提醒该值会为您提供原始 JSON,而不是 [Object object])。

您应该通过确保服务器发送 JSON 来解决此问题:

Content-Type: application/json

由于您似乎正在使用 PHP,因此您可以这样做:

header("Content-Type: application/json");

您还应该删除 datatype: 'json' 或将其更改为 dataType: 'json'

关于javascript - JSON 的 Ajax 调用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33277338/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com