jQuery 和 JSON:从具有多个值的数组链接 select

jQuery and JSON: chained select from an array with multiple values

我有一个 JSON 文件 (json/cities.json),它以下列形式将我国各州与其城市相关联:

{
    "State #1": [
        "City #1 from State #1",
        "City #2 from State #1",
        "City #3 from State #1"
    ],
    "State #2": [
        "City #1 from State #2",
        "City #2 from State #2",
        "City #3 from State #2"
    ]
}

我也有一个 HTML select 与状态,像这样:

<select id="state" name="state">
    <option value="State #1"> State #1 </option>
    <option value="State #2"> State #2 </option>
</select>

和一个空 HTML select 城市:

<select id="city" name="city"></select>

我想要做的是用 JSON 键(州)过滤的值填充城市的 HTML select。

我正在使用以下 jQuery 脚本:

$('#state').on('change', function () {
    var state = $(this).val(), city = $('#city');
    $.getJSON('json/cities.json', function (result) {
        $.each(result, function (i, value) {
            if (i === state) {
                 var obj = city.append($("<option></option>").attr("value", value).text(value));
                 console.log(obj);
            }
        });
    });
});

问题是 select 应该用城市填充,而 console.log returns 以下标记甚至没有改变:

<select name="city" id="city">
    <option value="City #1 form State #1, City #2 from State #1, City #3 from State #1">
        City #1 from State #1, City #2 from State #1, City #3 from State #1
    </option>
</select>

也就是说,值作为一个值返回,而它应该是多个值(每个值用逗号分隔)。

您正在遍历各州而不是城市。 result[state] 为您提供迭代的城市数组。

P.S。代码中的 url 部分只是为了让它在代码段中工作

$('#state').on('change', function () {
    var state = $(this).val(), city = $('#city');
    city.empty();
    var url = URL.createObjectURL(new Blob(['{"State #1":["City #1 from State #1","City #2 from State #1","City #3 from State #1"],"State #2":["City #1 from State #2","City #2 from State #2","City #3 from State #2"]}'], {type:'application/json'}));
    $.getJSON(url, function (result) {
        if (result[state]){
            $.each(result[state], function (i, value) {
               city.append($("<option></option>").attr("value", value).text(value));
            });
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="state" name="state">
    <option value="State #1"> State #1 </option>
    <option value="State #2"> State #2 </option>
</select>
<select id="city" name="city"></select>

我的建议:

$('#state').on('change', function () {
  var state = $(this).val(), city = $('#city');
  $.getJSON('json/cities.json', function (result) {
    var values = result[state];
    if (values != undefined && values.length > 0) {
      city.find('option').remove();
      $(values).each(function(index, element) {
        city.append($("<option></option>").attr("value", element).text(element));
      });
    }
  });
});

这是一个工作示例。我改变了一些东西来让它工作;代码中的注释。

首先,我在文档中嵌入了 JSON 以使其在代码片段中起作用。更改此变量的来源非常简单。您也可以继续更改此版本中的 JSON,您会看到更改更新。

我没有遍历所有州并查看它是否与 selected 州匹配,而是利用 JSON 中的结构按名称为城市编制索引。如果有很多状态,这会更有效率,而且更容易编程。

我还在州标识符下的列表中的 cities 上添加了缺失的迭代。

我在列表中添加了一个城市清理,以便在列表更改时也能,否则城市列表将包括所有 [=32]中的城市=]所有 个州 selected。

虽然不是绝对必要的,但我认为将 selected, disabled 选项添加到状态 <select> 是一个很好的做法 - 它强制用户进入 select 状态并强制城市列表更新(否则状态 1 默认为 selected,但需要做更多工作来填充初始 selection 的列表,因为当元素时不会设置 onchange被首先定义)。

/*
I'm embedding the JSON right in the page, but you'd 
use AJAX, of course.  You might want to pull this data just 
once or - if, it changes frequently and 
interaction with the form is prolonged, pull it
periodically, behind the scenes with a setInterval so the 
user doesn't have to wait for a web request.
*/
function get_state_data(){
   return JSON.parse($('#json').val())
};

// set the event handler after the doc is ready - 
// make sure it's set _after_ the elements it changes 
// are in the DOM
$(document).ready(function() {
  $('#state').on('change', function() {
    var state = $(this).val(),
      city = $('#city'),
      data = get_state_data();
    city.html(""); // clear out old cities
    // make use of the key->value structure of json,
    // rather than iterating over all cities
    if (data[state] === undefined)
      alert("No such state in data! :( ");
    else {
      //we have to iterate over each city
      for (c in data[state]) {
        city.append(
           $("<option></option>").attr("value", data[state][c]).text(data[state][c])
        );
      }
    }
  });
});
textarea {
  width: 95%;
  margin: auto;
  height: 10em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <textarea id='json'>
    { "State #1": [ "City #1 from State #1", "City #2 from State #1", "City #3 from State #1" ], "State #2": [ "City #1 from State #2", "City #2 from State #2", "City #3 from State #2" ] }
  </textarea>
</div>
<select id="state" name="state">
  <option disabled selected value=''>Select a state</option>
  <option value="State #1">State #1</option>
  <option value="State #2">State #2</option>
</select>
<select id="city" name="city"></select>