Read about ...
  • Apple Mac & OSX
  • Internet & Social Media
  • Reviews
  • Security
  • SEO & Marketing
  • Web Design
  • Web Hosting
  • RSS RSS Feed

    Looping Through JSON & Wrapping Subsets with JQuery

    So, you have just received JSON data via an AJAX request and you need to loop through, what is effectively an associative array, wrapping every few generated html records in a wider tag set, creating record subsets and allowing you to generate the requisite code for a slider or pager. How do you go about acheiving this?

    The request for JSON in JQuery will look something like this:

    $.ajax({
    	type: "POST",
    	url: "/your-url.com",
    	dataType: "json",
    	success: function(data) {
    		...
    	}
    });
    

    Within the success response handler function you will then want to do the requisite looping and wrapping accordingly, by whatever means is favored, be it using custom object functions or otherwise. By way of example you might use the following code:

    //clear out the existing results
    $("#results").empty();
    
    //initialize counters
    var counter = 0;
    var setcounter = 0;
    var numberSubset = 6;
    
    //iterate through JSON array
    for(item in data) {
    
    	//assign this object to a var
    	var project = list[item];
    
    	//add project details to results
    	$("#results").append('<div id="'+ project.id +
    		'" class="resultitem"> ... </div>');
    
    	//add new results group set
    	var resultitems = $('#results > .resultitem');
    	if ($(resultitems).size() == numberSubset) {
    
    		//wrap current resulitems in resultgroup
    		$(resultitems).wrapAll('<div id="set-' +
    			setcounter +'" class="resultgroup"></div>');
    
    		//increment set number counter
    		setcounter++;
    	}
    
    	//increment record counter
    	counter++;
    }
    
    //catch residual resultitems and wrap in resultgroup
    $('#results > .resultitem').wrapAll('<div id="set-' +
    	setcounter +'" class="resultgroup"></div>');
    

    And there you have it, a quick and easy way to loop through a JSON array, creating subsets of records in the html output using JQuery.

    Bookmark This Article:
    • Digg
    • del.icio.us
    • Facebook
    • Google
    • Furl
    • LinkedIn
    • Live
    • Ma.gnolia
    • MySpace
    • Pownce
    • Reddit
    • StumbleUpon
    • Technorati
    • E-mail this story to a friend!
    • Print this article!
    • Yahoo! Buzz
    • YahooMyWeb
    • TwitThis

    Why not join the conversation? Leave a reply.