javascript - Trouble trying to use JSON and JS with jQuery
问题描述
I'm trying to get the field 'sigla' from a JSON file and put it on a HTML 'option object', but it's refusing to work as it should.. hope some of you out there can help me with that!
This is a sample of the JSON file:
{
"estados": [
{
"sigla": "AC",
"nome": "Acre",
"cidades": [
"Acrelândia",
"Assis Brasil"
]
},
{
"sigla": "AL",
"nome": "Alagoas",
"cidades": [
"Água Branca",
"Anadia"
]
}, ...
]
}
Script:
<script>
$.getJSON("json/estados.json", function (data){
$.each(data.estados, function (keyEstados, valEstados){
var output = '';
output += '<option value="" disabled="disabled" selected>UF</option>';
$.each(valEstados.sigla, function (keySigla, valSigla){
output += '<option value="' + valSigla + '">' + valSigla + '</option>';
});
$('#selection').html(output);
});
});
</script>
Where it should fit in:
<div class="col-sm-6">
<div class="inputBox">
<div class="inputText">Selecione seu estado*
<select id="selection" name="estado_php" required>
<option value="" disabled="disabled" selected>UF</option>
</select>
</div>
</div>
</div>
解决方案
您是否尝试过在浏览器中使用“开发者”模式在代码中设置断点来调试它?例如,在 Firefox 上,菜单有一个“Web Developer”->“Debugger”的顶级条目。
如果你这样做,我想你会发现你的循环混淆了。第一个循环看起来不错
$.each(data.estados, function (keyEstados, valEstados){...
应该与列表开始匹配
"estados": [...]
但是,我认为第二个循环不会开始
$.each(valEstados.sigla, function (keySigla, valSigla){
是需要的。我认为您的代码需要看起来更像这样:
$.getJSON("json/estados.json", function (data){
var output = '';
output += '<option value="" disabled="disabled" selected>UF</option>';
$.each(data.estados, function (keyEstados, valEstados){
output += '<option value="' + valSigla + '">' + valSigla + '</option>';
});
$('#selection').html(output);
});
(未经测试,但它基本上摆脱了内部循环)。
推荐阅读
- c# - 对象没有服务时间的定义
- symfony - 在同一个树枝文件中有两种不同形式的问题
- postgresql - UPSERT - INSERT ... ON CONFLICT 失败,基于函数的索引作为 'lower()' 唯一约束
- sql - 如何根据非重复列中的逻辑消除某些列中的重复项
- python - 使用 Pandas 读取带有变量类型列的 Excel
- reactjs - 我应该提到 react-native 作为我的 react-native 库的依赖项吗?
- asp.net - Why does ReturnUrl return null parameter though it shows up in the adress bar?
- c# - 本地化文件在 MVC ASP.NET Core 2.2 中无法有效呈现 Razor 页面
- c# - 在 C# 中启用/禁用脚本无法正常工作
- python - 在Python中获取文本后的数字