1

我有这个调用 php 文件以返回 JSON 字符串的 javascript 文件。Chrome 开发工具在 javascript 代码的第 10 行抛出错误。我知道该错误与缺少括号有关,但对于我和其他 3 个看过它的人来说,语法是正确的。

var request = new XMLHttpRequest();
var listings = [];
var json;
var url = "getListing.php";
request.open("GET", url, true);
request.send();
request.onreadystatechange = function(e)
{
if(request.readyState == 4){
    json = JSON.parse(request.responseText);

    for(var x = 0; x < json.length; x++){
        var list = new listingInfo();
        list.category = json[x].category;
        list.date = json[x].dateListed;
        list.description = json[x].description;
        list.id = json[x].listingID;
        list.title = json[x].title;
        list.userID = json[x].userID;
        listings.push(list);
    }   
}
console.log(listings);
}

这是php文件

<?php
session_start();
$con = mysql_connect("localhost", "listAdmin", "hermes");
if(!$con)
{
    die('Could not connect: ' . mysql_error());
}

mysql_select_db("GregsList", $con)
    or die("Unable to select database:" . mysql_error());

$result = mysql_query("SELECT * FROM Listings WHERE userID = '$_SESSION[userID]' ORDER BY dateListed DESC");

#converts to json
$rows = array();
while($r = mysql_fetch_assoc($result)) 
{
        $rows[] = $r;
}

#If you want to see if correct json is printing use ---> print json_encode($rows);

return json_encode($rows);
?>
4

1 回答 1

2

request.readyState == 4 还不够,你应该在你的 php 脚本中添加 request.status== 200 替换return json_encode($rows);print json_encode($rows);

于 2013-11-04T06:16:27.720 回答