我正在进行AJAX调用,我得到以下内容:
{"status":"Results Found","errorcode":"0","result":[{"name":"test","id":"1"},{"name":"some","id":"2"}]}
我想对结果元素做的是使用javascript制作无序列表。例如:
<ul>
<li> test </li>
<li> some </li>
</ul>
有人可以协助吗?
由于
答案 0 :(得分:2)
这也是一个很好的做法:
var q = '{"status":"Results Found","errorcode":"0","result":[{"name":"test","id":"1"},{"name":"some","id":"2"}]}';
var o = $.parseJSON(q);
alert(o.status); // for test, remove it
alert(o.errorcode); // for test, remove it
var ul = "<ul>";
for (var i = 0; i < o.result.length; i++) {
alert(o.result[i].name + " = " + o.result[i].id); // for test, remove it
ul += "<li>" + o.result[i].name + "</li>";
}
ul += "</ul>"; // final html, use it
答案 1 :(得分:1)
这样的事情应该有效:
var html = "<ul>";
for (var i = 0; i < data["result"].length; i++) {
html += "<li>" + data["result"][i] + "</li>";
}
html += "</ul>";
然后您可以使用html
字符串动态创建列表。
答案 2 :(得分:0)
这样做:
// TODO: global variable 'ajax' should be an XMLHttpRequest instance.
// TODO: change last line 'document.body.appendChild' to append where you need to.
var response = JSON.parse( ajax.responseText );
var results = response.result;
var ul = document.createElemnt('ul');
var li;
for (var i = 0; i < results.length; i++) {
li = document.createElement('li');
li.innerHTML = results[ i ].name;
ul.appendChild(li);
}
document.body.appendChild(ul);