使用jquery从json文件加载组合框中的数据

时间:2015-05-20 09:10:43

标签: jquery json

将countries列表保存在countries.json文件中。 如果从json文件将国家/地区加载到组合框中,则不会产生任何结果 这是你的代码细节。在加载页面时,国家/地区应该在组合框中。

countries.json

[
  {name: 'Afghanistan', code: 'AF'},
  {name: 'Ã…land Islands', code: 'AX'},
  {name: 'Albania', code: 'AL'},
  {name: 'Algeria', code: 'DZ'},
  {name: 'American Samoa', code: 'AS'},
  {name: 'AndorrA', code: 'AD'},
  {name: 'Angola', code: 'AO'},
  {name: 'Anguilla', code: 'AI'},
  {name: 'Antarctica', code: 'AQ'},
  {name: 'Antigua and Barbuda', code: 'AG'},
  {name: 'Argentina', code: 'AR'},
  {name: 'Armenia', code: 'AM'},
  {name: 'Aruba', code: 'AW'},
  {name: 'Australia', code: 'AU'},
  {name: 'Austria', code: 'AT'},
  {name: 'Azerbaijan', code: 'AZ'},
  {name: 'Bahamas', code: 'BS'},
  {name: 'Bahrain', code: 'BH'},
  {name: 'Bangladesh', code: 'BD'},
  {name: 'Barbados', code: 'BB'},
  {name: 'Belarus', code: 'BY'},
  {name: 'Belgium', code: 'BE'}
  ]

Html文件-demo.html

    <!doctype html>
    <html>
    <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    </head>
    <body>
    <select id="orgcountry" class="form-control input-md"></select>
    <script>
    $(document).ready(function() {
    var $select = $('#orgcountry');

$.getJSON('countries.json', function(data) {
$select.html('');
//iterate over the data and append a select option
$.each(data, function(key, val){
$select.append('<option id="' + val.code+ '">' + val.name + '</option>');
})

});
});
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

你编写jquery代码很好。问题是json文件不正确。 json对象的名称和值需要是双引号,如下所示

[ 
  {"name": "Afghanistan", "code": "AF"},
  {"name": "Ã…land Islands", "code": "AX"},
  {"name": "Albania", "code": "AL"},
  {"name": "Algeria", "code": "DZ"},
  {"name": "American Samoa", "code": "AS"},
  {"name": "AndorrA", "code": "AD"},
  {"name": "Angola", "code": "AO"},
  {"name": "Anguilla", "code": "AI"},
  {"name": "Antarctica", "code": "AQ"},
  {"name": "Antigua and Barbuda", "code": "AG"},
  {"name": "Argentina", "code": "AR"},
  {"name": "Armenia", "code": "AM"},
  {"name": "Aruba", "code": "AW"},
  {"name": "Australia", "code": "AU"},
  {"name": "Austria", "code": "AT"},
  {"name": "Azerbaijan", "code": "AZ"},
  {"name": "Bahamas", "code": "BS"},
  {"name": "Bahrain", "code": "BH"},
  {"name": "Bangladesh", "code": "BD"},
  {"name": "Barbados", "code": "BB"},
  {"name": "Belarus", "code": "BY"},
  {"name": "Belgium", "code": "BE"}
  ]