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

时间:2012-09-05 15:05:09

标签: php javascript json

在我的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。任何人可以提供的帮助都会很棒。

2 个答案:

答案 0 :(得分:2)

我认为你的问题在这里:

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

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

在填充debugging元素以显示响应的代码中,你做对了。

答案 1 :(得分:0)

构造结果的代码是错误的。它应该是:

$result_array = array();
while($row = mysql_fetch_assoc($result))
{
   $result_array[$row['id']] = $row;
}