我试图用数据库中的数据填充组合框。
当我访问mystream.php时?theLocation = NewYork 我得到了这个JSON响应
RESULT
{"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));
答案 0 :(得分:3)
两个问题:
您的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
,它有你的数组。
如果你修复了这些,你的循环应该开始工作。
如果您不想, 相反,你可以让你的JSON定义一个数组而不是一个具有引用数组的单个属性的对象:
result.result
您还没有显示创建[
{
"theID": "36",
"theStream": "0817-05131",
"theLabel": "hgjbn",
"theLocation": "NewYork"
},
(and so on)
]
的PHP代码,因此我无法向您展示如何执行此操作,但A)您不需要,{{1事情很好,B)如果你愿意的话,我相信你能搞清楚。