2013-12-22 17 views
0

當我使用json_encode($array)我得到的數據正常,但是當我使用的是循環出現以下錯誤陣列中json_encodeAJAX失敗,而從同時獲得數據()循環在PHP

[object Object] parsererror SyntaxError: Unexpected token {


我使用Ajax來得到的functions.php

$(function() { 
$('#get').click(function(){ 
     $.ajax({ 
     url: 'http://android.ezinfotec.com/functions.php', 
     type : 'GET', 
     data : 'method=getquestions',   
     dataType : 'json', 
     success : function(s) { 
      console.log(s); 
     }, 
     error: function(XMLHttpRequest,textStatus,errorThrown) 
     { 
      console.log(XMLHttpRequest+' '+textStatus+' '+errorThrown); 
     } 
    }); 
}); 
}); 

的functions.php的JSON數據

<?php 
header('Content-type: application/json'); 
include("connect.php"); 
if($_GET['method'] == 'getquestions') 
{ 
$query = mysql_query("select * from questions"); 
while($fetch = mysql_fetch_array($query)) 
{ 

$output = array(
       "id" => $fetch['id'], 
       "answers" => $fetch['answers'], 
       "status" => $fetch['ans_status'], 
       "postedon" => substr($fetch['month'],0,3).' '.$fetch['day'].' '.$fetch['year'], 
       "question" => $fetch['question'], 
       "category" => $fetch['category'], 
       "parent" => $fetch['parentcategory'], 
       "authorid" => $fetch['author'], 
       "authorname" => $fetch['author_name']     
       ); 
       echo json_encode($output); 
} 

} 

在上面的php代碼中,如果我刪除while循環並簡單地爲變量定義自定義值,我會在html頁面中獲得完美的數據。

注意:沒有跨域問題,因爲我有很多的功能,除了getquestions();

您可以在http://android.ezinfotec.com/functions.php?method=getquestions

+0

'mysql_'被折舊...使用'mysqli_'代替! – NoobEditor

+0

您可能沒有完全閱讀我的問題。檢查最後一行你可以找到json輸出。 –

+0

爲什麼你不想一次發送所有數據? – MTahir

回答

3

檢查JSON輸出工作你會希望將所有的記錄追加到而是一個數組和json_encode。它失敗了,因爲多個json對象被髮回到它只期望一個的頁面。

$output = array(); 
while (...) { 
    $output[] = ... 
} 
// add a header too 
header('Content-Type: application/json'); 
echo json_encode($output); 

對不起,這不是完整的代碼。從我的手機這樣做是相當煩瑣的。

+0

我對自己有同樣的問題。你能幫我實現同樣的目標嗎? –

0

我已經取得的成就,我想,

@StuartWakefield謝謝你的提示。

我做了以下以獲得適當的JSON的結果,而不parseerror

$query = mysql_query("select * from questions"); 
while($fetch = mysql_fetch_array($query)) 
{ 

$output[] = array(
       "id" => $fetch['id'], 
       "answers" => $fetch['answers'], 
       "status" => $fetch['ans_status'], 
       "postedon" => substr($fetch['month'],0,3).' '.$fetch['day'].' '.$fetch['year'], 
       "question" => $fetch['question'], 
       "category" => $fetch['category'], 
       "parent" => $fetch['parentcategory'], 
       "authorid" => $fetch['author'], 
       "authorname" => $fetch['author_name']     
       ); 
} 
       echo json_encode($output); 

} 

的每個記錄使用while循環被存儲在其它陣列($輸出[])中,一旦while循環耗盡我簡單地進行編碼生成$ output array