在我的JavaScript我有這個json工作得很好。json數組格式json_encode php
{
"sEcho": 1,
"iTotalRecords": 58,
"iTotalDisplayRecords": 58,
"aaData": [
["Gecko","Firefox 1.0","Win 98+/OSX.2+","1.7","A"],
["Gecko","Firefox 1.5","Win 98+/OSX.2+","1.8","A"],
["Gecko","Firefox 2.0","Win 98+/OSX.2+","1.8","A"],
["Gecko","Firefox 3.0","Win 2k+/OSX.3+","1.9","A"],
["Gecko","Camino 1.0","OSX.2+","1.8","A"],
["Gecko","Camino 1.5","OSX.3+","1.8","A"],
["Gecko","Netscape 7.2","Win 95+/Mac OS 8.6-9.2","1.7","A"],
["Gecko","Netscape Browser 8","Win 98SE+","1.7","A"],
["Gecko","Netscape Navigator 9","Win 98+/OSX.2+","1.8","A"],
["Gecko","Mozilla 1.0","Win 95+/OSX.1+","1","A"]
]
}
但是,這當然是硬編碼,我想使aaData動態。我打算做這樣的事情$就我的PHP有這個代碼
$result = mysql_query("SELECT * FROM Persons");
$newArray = array();
while($row =mysql_fetch_array($result)){
$newArray[] = $row;
}
echo json_encode($newArray);
,並從json_endcode數據是
[
{"0":"1","P_Id":"1","1":"zamor","LastName":"zamor","2":"credit","FirstName":"credit","3":"Giftcard","Address":"Giftcard","4":"Finance","City":"Finance"},{"0":"3","P_Id":"3","1":"zamor3","LastName":"zamor3","2":"credit","FirstName":"credit","3":"Giftcard","Address":"Giftcard","4":"Finance","City":"Finance"},{"0":"4","P_Id":"4","1":"zamor4","LastName":"zamor4","2":"credit","FirstName":"credit","3":"Giftcard","Address":"Giftcard","4":"Finance","City":"Finance"},{"0":"5","P_Id":"5","1":"zamor5","LastName":"zamor5","2":"credit","FirstName":"credit","3":"Giftcard","Address":"Giftcard","4":"Finance","City":"Finance"},{"0":"2","P_Id":"2","1":"zamor2","LastName":"zamor2","2":"credit","FirstName":"credit","3":"Giftcard","Address":"Giftcard","4":"Finance","City":"Finance"}
]
注意到它有[{...}]而不是[...] ] 所以如果我更換我的aaData(硬編碼的,與上面這個)它讓我錯誤。我怎樣才能讓我的PHP代碼返回aaData中的東西。 謝謝
替換第一個代碼塊的,你告訴是不是一個JSON字符串,也不是JavaScript對象符號的表示。它是一個擁有數組集合的數組。在您創建的數組中返回數組中的json_encode將輸出一個有效的JSON字符串。您需要相應地處理該字符串。使用'.getJSON()'會得到你的那個對象(JSON解析和所有),然後你可以使用'$ .each'遍歷JSON字符串的集合。 – Ohgodwhy 2012-07-30 20:38:13
可能的重複[獲取正確的JSON格式](http://stackoverflow.com/questions/11447582/getting-correct-json-format) – mario 2012-07-30 20:39:29