jQuery和JSON:从具有多个值的数组中进行链式选择

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

本文关键字:数组 选择 JSON jQuery      更新时间:2023-09-26

我有一个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 id="state" name="state">
    <option value="State #1"> State #1 </option>
    <option value="State #2"> State #2 </option>
</select>

以及为城市选择的空HTML:

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

我要做的是用键(state)过滤的JSON值填充城市的HTML选择。

我正在使用以下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);
            }
        });
    });
});

问题是,当console.log返回以下标记时,应该填写城市的选择甚至没有改变:

<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]为您提供了一个城市阵列,对其进行迭代。

附言:代码中的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,您将看到更改的更新。

我没有迭代状态并查看它是否与所选状态匹配,而是使用JSON中的结构按名称对城市进行索引。如果有很多州,这会更有效率,而且无论如何都更容易编程。

我还在状态标识符下添加了列表中城市的缺失迭代。

我添加了对列表中城市的清除,这样当列表也发生更改时,或者城市列表将包括所有来自的城市所有曾经选择的州。

虽然不是绝对必要的,但我认为将选中的、禁用的选项添加到状态<select>是一种很好的方式-它迫使用户选择一个状态并强制更新城市列表(否则默认情况下会选择状态1,但需要做更多的工作来填充初始选择的列表,因为在第一次定义元素时不会设置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>