开发者

How do I parse the following AJAX reponse in Javascript?

开发者 https://www.devze.com 2023-04-03 03:11 出处:网络
I am making an AJAX call and I get the following: {\"status\":\"Results Found\",\"errorcode\":\"0\",\"result\":[{\"name\":\"test\",\"id\":\"1\"},{\"name\":\"some\",\"id\":\"2\"}]}

I am making an AJAX call and I get the following:

{"status":"Results Found","errorcode":"0","result":[{"name":"test","id":"1"},{"name":"some","id":"2"}]}

What I want to do with the res开发者_如何学JAVAult element is to make a unordered list using javascript. For example:

<ul>
<li> test </li>
<li> some </li>
</ul>

Can someone assist?

Thanks


and this is a good practice too:

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


Something like this should work:

var html = "<ul>";
for (var i = 0; i < data["result"].length; i++) {
  html += "<li>" + data["result"][i] + "</li>";
}
html += "</ul>";

and then you can use the html string to dynamically create a list.


This will do it:

// 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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号