2013-11-04 76 views
1

我有這個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); 
?> 
+0

其替換return json_encode($rows);而不是錯誤所在的json內容,是嗎? –

+0

日誌request.responseText看看是否有效 – farmer1992

+0

可以請你插入一個console.log JSON.parse之前:console.log(request.responseText) –

回答

2

request.readyState == 4是不夠的,你應該添加request.status == 200 在你的PHP腳本print json_encode($rows);

+0

這不起作用 – Carter

+1

你應該在發送請求之前註冊回調函數request.onreadystatechange = function(e)request.send() –

+0

這樣做。仍然得到相同的錯誤 – Carter

相關問題