tags:

views:

52

answers:

1

Given the following:

What I would like to happen: 1. Find all Span TAGS with class="location" 2. Loop through these and create a JSON string to post to the server

// Determine how many there are
var postText = $("#container").html();
var numFound = $("span.location").length;
var countVar = 0;

//Loop through all the Locations
$( "span.location" ).each( function() {

    // Keep a count
    countVar = countVar + 1;
    // Send at the end
    if (countVar == numFound) {
        // Send some JSON object to the server [{"locationID":"16","locationDesc":"XXXX"}....]
    }

});

Can someone help me understand how to create a JSON object like: [{"locationID":"16","locationDesc":"XXXX"}, {"locationID":"111","locationDesc":"XXXX"}, {"locationID":"12","locationDesc":"XXXX"}, {"locationID":"11","locationDesc":"XXXX"}]

I'd like to build this object via a LOOP, so some way to append over and over.

thxs

+1  A: 

JSON does not have objects. JavaScript has objects, and JSON has strings. Use json2.js to convert between the two.

Ignacio Vazquez-Abrams
Do I need something else like json2.js if I already have JQUERY?
AnApprentice
Presumably there's some some of encoder/decoder in jQuery, but I've never used it.
Ignacio Vazquez-Abrams
JSON2.js tells me how to access the string. I'm not see how to create this string, especially while looping to build it. ideas?
AnApprentice
You *don't* create the string. You create the object in JavaScript, and then shove it through `stringify()` to turn it into a string.
Ignacio Vazquez-Abrams
Can you show me how to do this in a loop, where it appends and builds the string?
AnApprentice
`a=Array();``o=Object();``o.foo=1;``o.bar=2;``a.push(o);``alert(stringify(a));`
Ignacio Vazquez-Abrams