2015-12-04 136 views
0

我想一個數組對象返回到我的jQuery的Ajax調用,但它似乎返回與數組長度字符串= 1

PHP代碼:在開發人員工具

$results = mysqli_query($link, $sql); 

if ($results->num_rows > 0) { 

    while ($row = $results->fetch_assoc()) { 


     $array = array($row['eventDate'], $row['time'] ,['data' => $row['time']]) ; 

     echo json_encode($array) ; 
    } 
} else { 
    echo "0 results"; 
} 

響應顯示:

["12_03_2015","0:00:00",{"data":"0:00:00"}]["12_03_2015","0:00:00",{"data":"0:00:00"}]["12_03_2015","0:00:00",{"data":"0:00:00"}] 

我的AJAX調用:

功能趨勢(數據){

$.ajax({ 
    url: "trendData.php", 
    cache: true, 
    type: "POST", 
    data: {arr:data}, 

    success: function (data) { 
     originalData=[]; 

     originalData.push(data) 
     trender(data) 
    } 
}); 

}

在用於網絡預覽窗口,它顯示一個數組:

enter image description here

我不能得到的數組,在這個例子中,3個對象,並獲得array.length 3

任何幫助將不勝感激。

enter image description here

+0

這是3數組元素,怎麼了?目前尚不清楚。 –

+0

當我調試data.length,它返回1 由於某種原因,我不能返回數組3 – user5451365

+0

因爲它是一個關聯數組看看開始'[[''你應該做'data [0] .length' –

回答

3

你應該收集的所有數據並返回它作爲一個JSON結果,並添加使JSON格式將被識別正確的HTTP頭(由@Flosculus建議):

$results = mysqli_query($link, $sql); 
$data = array(); 

if ($results->num_rows > 0) { 
    while ($row = $results->fetch_assoc()) { 
     $data[] = array($row['eventDate'], $row['time'] ,['data' => $row['time']]) ;   
    } 

    header('Content-Type: application/json'); 
    echo json_encode($data) ; 
} else { 
    echo "0 results"; 
} 
+0

多數民衆贊成好,我也會改變else語句更多與Javascript兼容,所以'if(data.length> 0 ){' – Flosculus

+0

我在原始問題中添加了一個屏幕快照 仍然變長= 1 – user5451365

+1

@ user5451365嘗試將'header('Content-Type:application/json')'放在php文件的頂部。 – Flosculus

0

我認爲你必須使用JSON.parse()來,如果你使用jQuery讓你的js腳本看起來就像

$.ajax({ 
url: "trendData.php", 
cache: true, 
type: "POST", 
data: {arr:data}, 

success: function (data) { 
    var data = JSON.parse(data); 

    //see length of array 
    console.log(data.length); 
} 
});