gpt4 book ai didi

php - 无法将 JSON.parse 与 json_encode 的结果一起使用

转载 作者:行者123 更新时间:2023-12-02 19:23:14 25 4
gpt4 key购买 nike

在我的 php 文件中,我有以下代码

//create SQL to select schedule
$sql = "SELECT * FROM `Schedule`";

//create result set
$result = mysql_query($sql);

$result_array[] = "";
while($row = mysql_fetch_assoc($result))
{
$result_array[$row['ID']] = $row;
}

echo json_encode($result_array);

在我的 HTML 文件中,我有以下代码

xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var schedArray = JSON.parse(xmlhttp.ResponseText);

alert(schedArray[0]["ID"]);
}
}
xmlhttp.open("GET","getSchedule.php?q="+year,true);
xmlhttp.send();

当我运行 HTML 代码时,出现此错误:Uncaught SyntaxError: Unexpected token u

我相信我的数据编码正确,因为正在运行

document.getElementById("txtHint").innerHTML=xmlhttp.responseText;

在我的就绪状态下,检查为我提供了一个包含正确数据的数组:

{"0":"","1":{"ID":"1","Team":"Louisiana-Monroe","playDate":"2011-09-03","Conference":"Sun Belt","Rank":null,"Bowl":"0","Site":"H"},"3":{"ID":"3","Team":"Oklahoma","playDate":"2011-09-17","Conference":"Big 10","Rank":"1","Bowl":"0","Site":"H"},"4":{"ID":"4","Team":"Clemson","playDate":"2011-09-24","Conference":"ACC","Rank":"21","Bowl":"0","Site":"A"},"5":{"ID":"5","Team":"Wake Forest","playDate":"2011-10-08","Conference":"ACC","Rank":null,"Bowl":"0","Site":"A"},"6":{"ID":"6","Team":"Duke","playDate":"2011-10-15","Conference":"ACC","Rank":null,"Bowl":"0","Site":"A"},"7":{"ID":"7","Team":"Maryland","playDate":"2011-10-22","Conference":"ACC","Rank":null,"Bowl":"0","Site":"H"},"8":{"ID":"8","Team":"North Carolina State","playDate":"2011-10-29","Conference":"ACC","Rank":null,"Bowl":"0","Site":"H"},"9":{"ID":"9","Team":"Boston College","playDate":"2011-11-03","Conference":"ACC","Rank":null,"Bowl":"0","Site":"A"},"10":{"ID":"10","Team":"Miami (FL)","playDate":"2011-11-12","Conference":"ACC","Rank":null,"Bowl":"0","Site":"H"},"11":{"ID":"11","Team":"Virginia","playDate":"2011-11-19","Conference":"ACC","Rank":null,"Bowl":"0","Site":"H"},"12":{"ID":"12","Team":"Florida","playDate":"2011-11-26","Conference":"SEC","Rank":null,"Bowl":"0","Site":"A"},"13":{"ID":"13","Team":"Notre Dame","playDate":"2011-12-29","Conference":"IND","Rank":null,"Bowl":"1","Site":"N"},"14":{"ID":"14","Team":"Murray State","playDate":"2012-09-01","Conference":"Ohio Valley","Rank":null,"Bowl":"0","Site":"H"},"15":{"ID":"15","Team":"Savannah State","playDate":"2012-09-08","Conference":"MEAC","Rank":null,"Bowl":"0","Site":"H"}}

我不明白为什么会收到此错误。我没有使用 JQuery,并且在 JavaScript 中包含了 json2.js。有人可以提供的任何帮助都会很棒。

最佳答案

我认为你的问题在这里:

var schedArray = JSON.parse(xmlhttp.ResponseText);

它应该是responseText,小写的“r”。发生的情况是,字符串 "undefined" 是解析器实际尝试解释的内容,而以“u”开头的字符串不能是有效的 JSON。

您在填充调试元素以显示响应的代码中得到了正确的结果。

关于php - 无法将 JSON.parse 与 json_encode 的结果一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12284424/

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