gpt4 book ai didi

javascript - 无法读取json编码的数据

转载 作者:搜寻专家 更新时间:2023-10-31 21:27:33 24 4
gpt4 key购买 nike

我正在开发一个 super 简单的基于 php 和 jQuery ajax 的聊天,但是我在通过 ajax 回调函数显示 json 编码的字符串时遇到了问题。

这是ajax请求:

$.ajax({
url: "/pages/core.chat.php",
type: "POST",
dataType: "json",
contentType: "application/json",
data: {'action' : 'loadChat'},

success: function(resp) {
$("#chatBody").html(resp.refreshChat);
}

});

这是来自 .php 文件

if ($_POST['action'] == 'loadChat') {   
$resp = array("refreshChat"=>$chat);
echo json_encode($resp);
}

其中 $chat 包含消息文本。我得到的只是一个空白页。此外,如果我发送不带 dataTypecontentType 参数的 ajax 请求并在不带 .refreshChat 的情况下运行回调,它会将 json 编码的字符串打印为它应该是 {"refreshChat":"chatmessage"},所以问题可能在于我传递这些参数的方式?只是猜测。我是 jQuery ajax 的新手,我已经检查、双重检查和三次检查,但我不知道我做错了什么。感谢任何可以创造魔法的人。

最佳答案

当使用 contentType: 'application/json' 时,您将无法依赖 $_POST 的填充。 $_POST 仅适用于表单编码的内容类型。

 $.ajax({
url: "/pages/core.chat.php",
type: "POST",
dataType: "json",
contentType:"application/x-www-form-urlencoded",
data: {'action' : 'loadChat'},

success: function(resp) {
$("#chatBody").html(resp.refreshChat);
}

});

如果你想发送 contentType:application/json 你实际上应该发送 JSON,但你没有这样做。

关于javascript - 无法读取json编码的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33949515/

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