1

I wrote a sample html which retrieves the JSON from servlet and displays. But only the thing is i want to know how to iterate the returned JSON response using jQuery. Currently i'm iteratng using javascript for loop.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="javascript/jquery-1.4.4.js"></script>

<!-- Here we need to load the trends on page load starts -->
<script>
 $(document).ready(function(){

     // now load the results from servlet

    // $("#trends").load("ReadRSSTrendsUsingServlet");

        // now get the result and retrieve each entry

        $.getJSON("ReadRSSTrendsUsingServlet",function(data){

       //  alert(data.trends[2]);

        for(var i=0;i<data.trends.length;i++)
        {
         $("#trends").append(data.trends[i]).append("<br>");

        }
            });


 });

 </script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div id="trends">
<!--  Here is the data to be loaded -->
</div>
</body>
</html>

After that it displaying the list of JSON values. My JSON object is like below

   {"trends":["test1","test2","test3","test4","test5"]}

What i want is to know the equivalent of jQuery for below steps

for(var i=0;i<data.trends.length;i++)
        {
         $("#trends").append(data.trends[i]).append("<br>");

        }
1
  • 1
    You'd be better off building your string in the loop, then doing a single $("#trends").append() after the loop. Or for this particular situation, use the .join() solution that was given. Commented Feb 19, 2011 at 18:44

5 Answers 5

3

You can use javascript join method in this case

var trends= ["1", "2", "3"];
$("#trends").append(trends.join('<br />'));
Sign up to request clarification or add additional context in comments.

3 Comments

I gave you a vote, since I thought this was a good way of accomplishing the end result. The only quibble I have is it doesn't answer the question, since Sukumar is looking for jQuery's version of a for loop, which this does not demonstrate.
@Jared Farrish, I think you've got it backwards here. Puneet suggested the most efficient way since it has less DOM manipulation and also happens to be much easier to read. I don't think they should be faulted for giving Sukumar a better answer than they were asking for ;)
@drewish - No, I don't think I have it backwards. Like I said, I voted for it. Look at the question - "replace for loop of javascript using jQuery". Is his example showing a for loop construct in jQuery for others that come along? No, it doesn't. Also, see my answer, which points to his answer. No fault to give here, just pointing out that by showing the $.each() syntax first (to answer the question), followed by "but this might be a better way" would have been a more complete answer. :)
2

You can use Jquery's $.each.

3 Comments

almost, from the documentation: The $.each() function is not the same as .each(), which is used to iterate, exclusively, over a jQuery object.
@Richard: Oops, my bad. Corrected.
Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.
1
$.each(data.trends, function(i, val){
    $("#trends").append(val+"<br>");
});

EDIT

As Puneet demonstrates in his answer, however, a more direct way of accomplishing what your code suggests in this specific case would be better done using a join, not a loop and append within the loop.

So while I think I've answered the question explicitly (how to replace a for loop using jQuery), and you'll not have any issue with the example above, I'd make sure and review Puneet's answer to see if that would work for you, as well.

replace for loop of javascript using jQuery

1 Comment

Good deal. :) jQuery makes a lot of things easier and neater.
1

$.each() would be the better choice. You'd want to use .each() on the result of a jQuery selection rather than a JavaScript object.

To quote the docs:

The $.each() function is not the same as .each(), which is used to iterate, exclusively, over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is a map (JavaScript object) or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time. (The value can also be accessed through the this keyword, but Javascript will always wrap the this value as an Object even if it is a simple string or number value.) The method returns its first argument, the object that was iterated.

Comments

0

jQuery.each.
you could also use the other for syntax :

for(var key in obj) 
    //do smth with obj[key]

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.