[英]jQuery reading JSON Data
所以我有一個數據庫使用 PHP 通過 JSON 將一大堆數據傳遞回 jQuery.. 我試圖從返回的數據中訪問各個列,但沒有運氣..
我的PHP:
header('Content-Type: application/json');
require 'database.php';
mysql_query('SET CHARACTER SET utf8');
$myjsons = array();
$qry = 'SELECT * FROM quotes ORDER BY id';
$result = mysql_query($qry);
while($row = mysql_fetch_assoc($result)){
$myjsons[] = json_encode(array($row));
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';
這是我的JS:
function getAll(){
jQuery.ajax({
url:'example.com/js/getAll.php',
async: true,
dataType: 'jsonp',
success:function(data){
$('.quoteList').append(data[0]);
}
});
}
目前將以下內容附加到元素:
[{"id":"1","text":"The most wasted of all days is one without laughter.","author":"E.E. Cummings","status":"1"}]
因此,例如.. 如果我希望 jQuery 通過 data[0] 到 data[92](最后一個)並將每個的作者附加到 .quoteList,我該怎么做? 我試過 data[0][1] 和 data[0][author]
您可以使用$.each()循環遍歷data
並附加author
:
$.each(data, function(i) {
$('.quoteList').append(data[i]['author']);
});
PHP 可能有缺陷,因為json_encode
被調用了兩次,這是不尋常的。 正如所寫的那樣,這會將行展平為 JSON 字符串,但仍然只是字符串,然后將 JSON 再次編碼為字符串數組。 這可能不是您想要的,因為它可以打印接收到的數據,但不能訪問將被解碼為字符串而不是對象的行的組件。
比較https://stackoverflow.com/a/6809069/103081 - 這里 PHP 用括號()
內的單個 JSON 對象回顯回調。
我懷疑該修復程序看起來像https://stackoverflow.com/a/15511447/103081 ,可以進行如下調整:
header('Content-Type: application/json');
require 'database.php';
mysql_query('SET CHARACTER SET utf8');
$myjsons = array();
$qry = 'SELECT * FROM quotes ORDER BY id';
$result = mysql_query($qry);
while($row = mysql_fetch_assoc($result)){
$myjsons[] = $row;
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';
一旦你有了這個,你應該為你的對象數組取回正確的 JSON,並且能夠在客戶端使用 @Felix 的代碼。
你需要在你的數據上使用循環,試試這個
success:function(data){
for (var i in data) {
$('.quoteList').append(data[i]);
}
}
這應該有效:(更新所有代碼:)
function getAll(){
jQuery.ajax({
url:'example.com/js/getAll.php',
async: true,
dataType: 'jsonp',
contentType: "application/json",
success:function(data){
var str = "";
$(data).each(function(index, item){
str += item.author + " ";
});
$('.quoteList').append(str);
}
});
}
你的問題在這里:
while($row = mysql_fetch_assoc($result)){
$myjsons[] = json_encode(array($row));
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';
你需要這樣的東西:
while($row = mysql_fetch_assoc($result)){
$myjsons[] = $row;
}
$myjsons['callback'] = $_GET['callback'];
echo json_encode($myjsons);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.