2014-02-16 33 views
-1

我搜索的結果錯誤,擡頭很多帖子..但我仍然無法弄清楚什麼是錯這個代碼在這裏:SyntaxError:JSON.parse:JSON數據後意外的非空白字符這裏有什麼錯誤?

我的Ajax調用:

function myCall3() { 
    $.ajax({ 
    type:"POST", 
    url:"ajax3.php", 
    dataType:"json", 
    success:function(response){ 
     alert(response[0]); 
    } 
    }); 
} 

我的MySQL/PHP代碼:

<?php 


// QUERY NEW VINE 
$array = array(); 
$myquery = "SELECT * FROM table1 ORDER BY rand() LIMIT 9"; 
$result = mysql_query($myquery) 
OR die("Error: $myquery <br>".mysql_error()); 

while($row = mysql_fetch_object($result)){ 
    $currentid = "$row->id"; 
    $currentname = "$row->name"; 
    $currenturl = "$row->url"; 
    $currentimage = "$row->image"; 
    $array[] =  array('id'=>$currentid,'url'=>$currenturl,'name'=>$currentname,'image'=>$currentimage); 

} 

echo json_encode($array); 

?> 

當我提醒錯誤,它說:

SyntaxError: SyntaxError: JSON.parse: unexpected character

回答

2

您在循環中一直覆蓋$ array,然後很快將其回顯出來。

$array = array('id'=>$currentid,'url'=>$currenturl,'name'=>$currentname,'image'=>$currentimage); 

echo json_encode($array); 

} 

你應該把每一行推到$ array變量,然後json_encode在循環之外。

$array = array(); 
$myquery = "SELECT * FROM table1 ORDER BY rand() LIMIT 9"; 
$result = mysql_query($myquery) 
OR die("Error: $myquery <br>".mysql_error()); 
while($row = mysql_fetch_object($result)) 
{ 
$currentid = "$row->id"; 
$currentname = "$row->name"; 
$currenturl = "$row->url"; 
$currentimage = "$row->image"; 
$array[] = array('id'=>$currentid,'url'=>$currenturl,'name'=>$currentname,'image'=>$currentimage); 

} 

echo json_encode($array); 

那麼你的JavaScript回調需要期待一個數組,而不是一個對象,即

console.log(response[0]); 

注意:您可以只直接推$排在$數組你想。

+0

當我使用這段代碼時,我會如何警告js中的所有url?我只是生產錯誤-.- –

+0

什麼錯誤?當你記錄響應和響應[0]時你會得到什麼?在這一點上它應該都是簡單的數組/對象表示法。 – thescientist

+0

當我記錄響應[0]它說:SyntaxError:JSON.parse:意外字符 –

0

您的輸出是這樣的:

{"id":123,"url":"http://.../","name":"Blah","image":"blah.png"}{"id":456,..... 

這不看我的權利:對

它看起來像你的JavaScript期待只有一行,所以嘗試LIMIT 1

+0

是的,它適用於limit1,但事情是我想得到9 :) ..我可能不得不改變變量數組在ajax調用? –

+0

@marc將結果收集到一個數組中,並將其立即進行串化和回顯。 –

1
$newArray = array(); 
while($row = mysql_fetch_object($result) { 
    $newArray[] = $row; 
} 
echo json_encode($newArray); 

然後,在JS中,你必須遍歷數組。

相關問題