1

I have web service which return json string like : d={"main0ID":"abc.es/main","main1ID":"ah/main"} I wanna append this to ul HTML control. How to iterate over json object string and append to ul?

Thanks...

2
  • Use For...In loop w3schools.com/js/js_loop_for_in.asp Commented Jun 19, 2012 at 4:01
  • using w3schools is an atrocity. So much misinformation on that site. Commented Jun 19, 2012 at 4:25

6 Answers 6

3

You could use for..in to iterate an object.

for (var key in d) {
  console.log(key, d[key]);
}
Sign up to request clarification or add additional context in comments.

Comments

1

Assuming you have ul like this

<ul id="ulItems"></ul>      

This will get the items from JSON and add to UL

$(function(){
    var items="";
    var data={"main0ID":"abc.es/main","main1ID":"ah/main"}
       $.each(data,function(index,item){
         items+="<option value='"+item+"'>"+item+"</option>";
       });       
    $("#ulItems").html(items);
});

Working sample : http://jsfiddle.net/tFpTu/4/

Always build a string and call the html function only once instead of calling the append function n times inside a loop

Comments

1

You can use .each() or .map() to iterate over the json object.

Comments

1
    $.ajax({           
                url: 'your url'
                type : 'POST',
                data : {/*any data*/},
                dataType:'json',
                success: function(msg) { //your json return
                for (i=0;i<msg.length;i++){
       alert(msg[i]['your_index']);
}

}

Comments

1

Both this methods can be used
But first method is considerably fast...

Check this tutorial ...

for (var keyIndex in d) {
    console.log(keyIndex, d[keyIndex]);
}

$.each(data,function(keyIndex,value){
    console.debug(inkeyIndexex,value);
});

Comments

0
$("#Button1").click(function () {
WebService.GetList(OnComplete, OnError);
function OnComplete(result) 
{
var items = "";
var value = Sys.Serialization.JavaScriptSerializer.deserialize(result, true);
for (var property in value) 
{              
items += "<option value='" + value[property] + "'>" + value[property] + "</option>";
}
$("#ContentPlaceHolder1_ListBox1").html(items);
}
function OnError(err)
{
alert("The error is :" + err.get_Message());
}
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.