1

我的示例中的 API 返回 id、名称对

  <categories>
   <category id="5" name="Bollywood"/>
   <category id="484" name="International"/>
   ...
  </categories>

我正在尝试有一个下拉列表,允许用户从选项中进行选择

 <select class="action" id="categoryEvent" onchange="change(value)" style="display: block">
   <script type="text/javascript">
      var url = "http://api.hungama.com/metroapp/categories.php?format=json";
      var id,name;
      var data = JSON.parse(url);
      data.category.forEach(function (content) {
   </script>
    <option value="id">name</option>  //id, name from api
   <script type="text/javascript">
        }
   </script>

我究竟做错了什么 ?

4

2 回答 2

2

看起来这是你想要的:

<select class="action" id="categoryEvent" onchange="change(value)"></select>
<script type="text/javascript">
    var url = "http://api.hungama.com/metroapp/categories.php?format=json";
    var id, name;
    var xhr;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var res = JSON.parse(xhr.responseText),
                data = res.category;
            for(var i = 0; i < data.length; i++) {
                var ele = document.createElement("option");
                ele.value = data[i].id;
                ele.innerHTML = data[i].name;
                document.getElementById("categoryEvent").appendChild(ele);
            }
        }
    }
    xhr.open("GET", url, true);
    xhr.send();
</script>
于 2012-06-24T20:51:56.987 回答
0

在 html 文档中,您应该在一侧声明 select html 元素,在另一侧声明 script 元素。

例如:

<select class="action" id="categoryEvent" onchange="change(value)">
</select>

<script type="text/javascript">
//manipulate the select
var select = document.getElementById("categoryEvent");
var newOption = document.createElement("option");
select.appendChild(newOption);
</script>
于 2012-06-24T20:45:46.110 回答