Reputation: 1539
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>");
}
Upvotes: 1
Views: 1850
Reputation: 49238
$.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
Upvotes: 1
Reputation: 41533
jQuery.each.
you could also use the other for
syntax :
for(var key in obj)
//do smth with obj[key]
Upvotes: 0
Reputation: 9378
$.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.
Upvotes: 1
Reputation: 1014
You can use javascript join method in this case
var trends= ["1", "2", "3"];
$("#trends").append(trends.join('<br />'));
Upvotes: 3