纯Java脚本填充数据以从JSON URL

时间:2018-10-19 14:03:11

标签: javascript html json

我有一个JavaScript函数可以从url中提取数据,但是当我尝试将其添加到下一个select元素时,我具有“ 未定义”选项。  这是我的代码。

首先选择元素

<div class="col-sm-6">
    <label class="font-bold no-margins">City/State *</label>
    <select name="city_state" class="form-control required" id="city_state"  onchange="populateSelect(this);">
        <?php
            echo '<option value="'.$city_state_data->id.'">'.$city_state_data->name.'</option>';
            foreach ($city_states as $city_state) {
                if($city_state_data->id != $city_state->id)
                {
                  echo '<option value="'.$city_state->id.'">'.$city_state->name.'';
                }
            }
        ?>
    </select>
  </div>

第二个选择元素

<div class="col-sm-12 col-xs-12">
<div class="form-group has-feedback">
    <label class="font-bold no-margins">Locale *</label>
    <select name="locale" class="form-control required" id="locale">
      <?php
        echo '<option value="'.$locale_data->id.'">'.$locale_data->name.'</option>';
          foreach ($locales as $locale) {
              if($locale_data->id != $locale->id){
                echo '<option value="'.$locale->id.'">'.$locale->name.'';
              }
          }
      ?>
    </select>
</div>

现在是我的JS脚本

<script>
function populateSelect(item) {
    // json url
    //var url = 'citystate/' + item.value + '/locales/';
var url = '[{"id":33,"name":"Boni Avenue"},{"id":34,"name":"Shaw Boulevard"}]';

    // empty select
    document.getElementById('locale').options.length = 0;

    var ele = document.getElementById('locale');
    for (var i = 0; i < url.length; i++) {
        // populate select element with json
        ele.innerHTML = ele.innerHTML +
            '<option value="' + url[i]['id'] + '">' + url[i]['name'] + '</option>';
    }
}
</script>

请帮助我如何在选择框中修复此 undefined 值。 谢谢。

1 个答案:

答案 0 :(得分:0)

如果要访问数据,则需要解析JSON 字符串。

function populateSelect(item) {
    var url = '[{"id":33,"name":"Boni Avenue"},{"id":34,"name":"Shaw Boulevard"}]';
    var data = JSON.parse(url);
    // empty select
    document.getElementById('locale').options.length = 0;

    var ele = document.getElementById('locale');
    for (var i = 0; i < data.length; i++) {
        // populate select element with json
        ele.innerHTML = ele.innerHTML +
            '<option value="' + data[i]['id'] + '">' + data[i]['name'] + '</option>';
    }
}

希望有帮助!