使用JSON数据填充下拉菜单

时间:2014-04-09 13:32:29

标签: javascript json

尝试使用JSON数据填充下拉菜单,但无法弄清楚我做错了什么。

JSON数据

{"dropdownValue1":"1x1","dropdownDisplay1":"1x1","dropdownValue2":"1x2","dropdownDisplay2":"1x2","dropdownValue3":"1x3","dropdownDisplay3":"1x3","dropdownValue4":"1x4","dropdownDisplay4":"1x4","dropdownValue5":"1x5","dropdownDisplay5":"1x5","dropdownValue6":"1x6","dropdownDisplay6":"1x6"}

的Java / HTML

<script type="application/javascript">
 $(function(){
        $("select#size").change(function(){
          $.getJSON("getDropdown",{id: $(this).val(), ajax: 'true'}, function(j){
            var options = '';
            for (var i = 0; i < j.length; i++) {
              options += '<option value="' + i + '">' + j[i] + '</option>';
        }
            $("select#size").append(options);
            })
        })
    })  </script>  

    <div class="input select orderBoxContent">
        <select name="size" id="size">
        </select>
        </div>

实际JSON请求

function getDropdown()
{
var people_no = $('#howmanypeople').val();
$.getJSON("../../getdata.php?getDropdown=yes&people_no="+people_no, function(response) {
        $('#getDropdown').html(response.getDropdown);
    });
}

干杯

赖安

2 个答案:

答案 0 :(得分:2)

你的JSON是一个对象,但你就像一个数组一样把它当作它。

var i;
for (i in j) {
  if (j.hasOwnProperty(i)) {
    // i = 'dropdownValue1'
    // j[i] = "1x1"
    // but the order is unknown
    options += '<option value="' + j[i] + '">' + j[i] + '</option>';
  }
}

答案 1 :(得分:0)

 $(function(){
        $("select#size").change(function(){
          $.getJSON("getDropdown",{id: $(this).val(), ajax: 'true'}, function(j){
            var i;
            for (i in j) {
              if (j.hasOwnProperty(i)) {
                // i = 'dropdownValue1'
                // j[i] = "1x1"
                // but the order is unknown
                options += '<option value="' + j[i] + '">' + j[i] + '</option>';
              }
            }
            $("select#size").append(options);
            })
        })
    })