使用javascript填充的列表的值

时间:2016-07-04 15:54:01

标签: javascript html html-lists

如何使用javascript获取的值填充选择列表?

我正在向.php网站发送GET请求,该网站以JSON格式提供响应。现在我想把我得到的那些行放到选择列表中。

<select id = "list" name=log size=50 style=width:1028px>

<script type="text/javascript">
window.onload = function () {

  var bytes=0;
  var url = "/test/log.php?q='0'";
  function httpGet(url)
  {
    var xhttp = new XMLHttpRequest();
    var realurl = url + bytes;
    xhttp.open("GET", url, true);
    xhttp.onload = function (e) {
        if (xhttp.readyState === 4) {
            if (xhttp.status === 200) {
                console.log(xhttp.responseText);
                var response=JSON.parse(xhttp.responseText);
                var log = response.key;
                bytes = log.length;
            }
        };
    xhttp.onerror = function (e) {
        console.error(xhttp.statusText);
      }
    };


    xhttp.send();
  }

  var updateInterval = 2000; 
  function update() {

    httpGet(url);
      setTimeout(update, updateInterval);
  }

  update();
}
</script>
</select>

我从log.php得到的回复是"{"key":"whole log file"}"。现在我想将该响应存储到列表中并每2秒填充一次。

1 个答案:

答案 0 :(得分:1)

JSON.parse之后循环返回字符串的内容。从中创建选项元素,并将其插入到选择中。

 var html = "";
 var obj = JSON.parse(xhttp.responseText);
 for(var key in obj) {
   html += "<option value=" + key  + ">" +obj[key] + "</option>";
 }
 document.getElementById("list").innerHTML = html;

请参阅JSBin

相关问题