1

I've got this JSON data coming back from my webservice.

How can I loop thru each line and append to a <ul>?

I've got the code below, but it does'nt seem to quite work. Thanks.

<script type="text/javascript">
        $(document).ready(function() {
            $('a#pop-video-link').click( function(e){
                // window.alert("test");
                var htm = "";
                // htm = $('ul.ad-thumb-list').html(htm);
                $("ul.ad-thumb-list li").remove();
                e.preventDefault();
                var src = $(this).attr('title');
                getResults(src);

             function getResults(str) {
               $.ajax({
                        type: "POST",
                        async: false,
                        contentType: "application/x-www-form-urlencoded",
                        dataType: "json",
                        data: 'data=' + str,
                        url: '/base/MyApi/MyPostFunction',
                        success: function(data){
                        var myData = JSON.parse(jsonString2);
                        var $grouplist = $('#groups');
                         $.each(myData, function() {
                          $('<li><a href="'+ this.url +'"/><img src="'+ this.src + '" class="image0"/></li>').appendTo($grouplist);
                         });
                        }
               });
                      }
             });
            }); 
             </script>

JSON Data trying to parse:

<value>[{"url":"/media/22.jpg","src":"/media/429.jpg"},{"url":"/media/44.jpg","src":"/media/55.jpg"},{"url":"/media/22.jpg","src":"/media/33.jpg"}]</value>

2 Answers 2

1

You have single dimensional array of objects so data[0].id would have id of first object and you also need to use length on it instead of count.

for (var i = 0; i < data.length; i++) {
         var n = data[i];
         $('ul.ad-thumb-list').append('<li><a href="'+n.url+'"/><img src="'n.src+'" class="image0"/></li>');
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can iterate through all your objects from data[0] with $.each

$.each(data[0], function(key, val) {
   $('<li><a href="'+ key +'"/><img src="'+ val +'" class="image0"/></li>')
        .appendTo('ul.ad-thumb-list');
});

see if this solves your problem.

1 Comment

thanks for the replies. I found that this seems to work ok: var myData = JSON.parse(jsonString); $(document).ready(function() { var $grouplist = $('#groups'); $.each(myData, function() { $('<li>' + this.url + '</li>').appendTo($grouplist); }); });

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.