我正在尝试使用 php 和 jquery 将数组传递给浏览器,但是当我尝试使用从 php 的 encode_json 返回的“数据”时,它出现未定义。我只是在学习 php、jquery 和 json,到目前为止还没有找到关于很多这些东西的很好的文档,尤其是 json,即使在我拥有的书中也是如此。提前致谢!
这是我拥有的 jquery 的精简版本
$(document).ready(function(){
var jsonResult;//I will want to be able to use the data in other functions
$.getJSON("json.php", function(data){
jsonResult = data;
var str;
var nuts = [203,204,205,207];
str = '<p>' + data[nuts[0]].NutraDesc + '</p>';
$('#stuff').html(str);
}
);
});
这是php:
include_once 'databasePHP.php';
$json_tst = $db->query( "SELECT def.Nutr_No, NutrDesc, Nutr_Val, Units
FROM nutr_def as def JOIN nut_data as data ON def.Nutr_No = data.Nutr_No
WHERE data.NDB_No = 1001 LIMIT 0, 2");
$food = array();
while($row = $json_tst->fetch(PDO::FETCH_ASSOC))
{
$Nutr_No = $row['Nutr_No'];
$food[$Nutr_No][] = array(
'NutrDesc' => $row['NutrDesc'],
'Nutr_Val' => $row['Nutr_Val'],
'Units' => $row['Units']
);
};
echo json_encode($food);
?>
它返回我在 jsonlint.com 上检查的这个 json,它说它是有效的:
{"203":[{"NutrDesc":"Protein","Nutr_Val":"0.85","Units":"g"}],"204":[{"NutrDesc":"Total lipid (fat)","Nutr_Val":"81.11","Units":"g"}]}