jquery - 使用 json 填充选择下拉列表

标签 jquery json

使用 jquery,我尝试使用 json 填充选择下拉列表。我正在尝试显示下面 json 中的国家/地区列表...

{  
"country":[  
  {  
     "China":[  
        {  
           "tarrifType":"Pay as you go"
        },
        {  
           "fixLine":"23p"
        }
     ],
     "India":[  
        {  
           "sms":"39p"
        },
        {  
           "fixLine":"3p",
           "sms":"59p"
        }
     ],
     "Poland":[  
        {  
           "mobile":"29p",
           "sms":"19p"
        },
        {  
           "tarrifType":"China Pass",
           "fixLine":"23p"
        }
     ]
  }
]
}

到目前为止,我尝试使用的 jquery 如下......

 $.getJSON("js/widgets/country-picker.json", function(result){
   $.each(result, function(i, field) {
  $('#js-rate-select').append($('<option>').text(field[1]).attr('value',    field[1]));
  });
 });

但它不会填充选择下拉列表或给出任何 DOM 错误。有什么建议我可以解决这个问题吗?我认为问题是因为 json 格式 - 我可以更改谢谢

最佳答案

您的 json feed 返回一个仅包含一个索引的数组,该索引是一个具有不同国家/地区的对象。因此,你应该说

result.country[0].China.tarrifType.

而且,您可以像这样迭代国家/地区:

$.each(result.country[0], function(country,data) { console.log(country); }

不过,我建议重做您的 JSON。你可以这样做:

var result = {
    "country": {
        "China": {
            "tarrifType": "Pay as you go",
            "fixLine": "23p"
        },
        "India": {
            "sms": "39p",
            "fixLine": "3p",
            "sms": "59p"
        },
        "Poland": {
            "mobile": "29p",
            "sms": "19p",
            "tarrifType": "China Pass",
            "fixLine": "23p"
        }
    }
};


$(function () {
    $.each(result.country, function (country, data) {
        console.log("Country : " + country);
        console.log(data); // data.fixLine, data.tarrifType, data.sms

        $('#selectbox').append('<option value="' + country + '">' + country + '</option>');

    });
});

jsfiddle在这里: Link to JSfiddle

关于jquery - 使用 json 填充选择下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30730496/

相关文章:

java - 如何获取客户端的时区

javascript - 如何触发文本输入事件以绕过应用程序的验证?

javascript - 在 json 数组中搜索特定属性

javascript - 将数组转换为 typescript 中的索引对象

jquery - 单击两次时添加事件类而不删除

javascript - 如何在 ui-router $stateChangeStart 中等待动画结束?

html - 如何在Notepad++中使用regex(正则表达式)删除所有不包含特定字符串的HTML和JSON代码?

javascript - 在 bash 脚本中获取带有 javascript 元素的 HTML 页面

c# - 使用 .NET 2.0 解析 JSON

json - 接收 Json API 响应并使用 Golang 发送 Json 响应