我有這個JavaScript文件調用一個PHP文件來返回一個JSON字符串。 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);
?>
其替換
return json_encode($rows);
而不是錯誤所在的json內容,是嗎? –日誌request.responseText看看是否有效 – farmer1992
可以請你插入一個console.log JSON.parse之前:console.log(request.responseText) –