首页 > 解决方案 > 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>

标签: javascriptjqueryjsonajax

解决方案


您是否尝试过在浏览器中使用“开发者”模式在代码中设置断点来调试它?例如,在 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);
});    

(未经测试,但它基本上摆脱了内部循环)。


推荐阅读