我正在尝试使用数据库中的数据填充组合框。
当我访问 mystream.php?theLocation=NewYork 时 我收到这个 JSON 响应
结果
{"result":
[{"theID":"36"},{"theStream":"0817-05131"},{"theLabel":"hgjbn"},{"theLocation":"NewYork"},
{"theID":"37"},{"theStream":"0817-05131"},{"theLabel":"hgjbn"},{"theLocation":"NewYork"},
{"theID":"40"},{"theStream":"0817-31334"},{"theLabel":"dsfg ghjg"},{"theLocation":"NewYork"}]}
应用这篇文章中的答案 loop through JSON result with jQuery
我想出了这个 JSON
$.getJSON(
'mystream.php',
'theLocation=NewYork',
function(result){
$('#cmbNewYork').empty();
$.each(result, function(i, item){
$('#cmbNewYork').append('<option value=' +item.theStream+ '>'+item.theLabel+'</option>');
alert(item.theStream);
});
}
);
我生成的组合框仅包含未定义的内容。
如何正确循环 JSON 响应?
谢谢
编辑(添加)
mystream.php
$sql = "SELECT * FROM Streams WHERE theLocation='$loc'";
$res = mysqli_query($conn,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('theID'=>$row['theID']),
array('theStream'=>$row['theStream']),
array('theLabel'=>$row['theLabel']),
array('theLocation'=>$row['theLocation'])
);
}
echo json_encode(array('result'=>$result));
最佳答案
两个问题:
您的 JSON 格式非常奇怪的主要问题:它是一个对象数组,每个对象都有一个名称/值对:
{"result": [
{"theID":"36"},
{"theStream":"0817-05131"},
{"theLabel":"hgjbn"},
{"theLocation":"NewYork"},
{"theID":"37"},
{"theStream":"0817-05131"},
{"theLabel":"hgjbn"},
{"theLocation":"NewYork"},
{"theID":"40"},
{"theStream":"0817-31334"},
{"theLabel":"dsfg ghjg"},
{"theLocation":"NewYork"}
]}
这是 12 个独立的对象。
您应该拥有具有所有这些属性的对象:
{
"result": [
{
"theID": "36",
"theStream": "0817-05131",
"theLabel": "hgjbn",
"theLocation": "NewYork"
},
{
"theID": "37",
"theStream": "0817-05131",
"theLabel": "hgjbn",
"theLocation": "NewYork"
},
{
"theID": "40",
"theStream": "0817-31334",
"theLabel": "dsfg ghjg",
"theLocation": "NewYork"
}
]
}
这是三个对象,每个对象都有四个属性。
重新编辑问题,您可以这样做:
while($row = mysqli_fetch_array($res)){
array_push($result,
array(
'theID'=>$row['theID'],
'theStream'=>$row['theStream'],
'theLabel'=>$row['theLabel'],
'theLocation'=>$row['theLocation']
)
);
}
请注意每个循环如何创建一个数组,而不是四个。
第二个问题是,您可能需要 result.result
,而不仅仅是 result
,在这一行:
$.each(result.result, function(i, item){
// ----------^^^^^^^
...因为 result
是您的总体匿名结果,它有一个属性 result
,其中包含您的数组。
如果你解决了这些问题,你的循环应该开始工作。
<小时/>如果您不愿意,您就不必执行result.result
操作。相反,您可以让 JSON 定义一个数组,而不是一个具有引用该数组的单个属性的对象:
[
{
"theID": "36",
"theStream": "0817-05131",
"theLabel": "hgjbn",
"theLocation": "NewYork"
},
(and so on)
]
您尚未展示创建 $result
的 PHP 代码,因此我无法向您展示如何执行此操作,但是 A) 您不需要,结果。结果
事情很好,而且 B) 如果你愿意,我相信你能弄清楚。
关于javascript - 如何正确循环 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32057445/