Reputation: 71
i am very new to play with JSON. I need to iterate over JSON response coming from AJAX, actually, i am fetching checkboxe values from db table in the form on 2,3,7,9,3. Now i am stuck with iteration on each number.
If you run following code in FF console area you will notice it is looping against each numeric NOT THE VALUE.
Please guide me.
var srv = {"services":"26,29"};
jQuery.each( srv.services, function(i, v) {
console.log( v );
});
Any help would be appreciated. THanks :)
Upvotes: 1
Views: 2366
Reputation: 344803
srv.services
is a string of comma separated values, so $.each()
won't work correctly. You can split() it into an array, though:
var srv = {"services":"26,29"};
jQuery.each(srv.services.split(","), function(i, v) {
console.log( v );
});
Working demo: http://jsfiddle.net/AndyE/veP4p/
You could also have your JSON service return an array instead of a string, e.g. {"services":[26, 29]}
. This would be done for you automatically at the server if you're using proper JSON-compliant methods to encode and if the data is an array.
Upvotes: 7
Reputation: 105091
You have to create an array first
var srv = {"services":"26,29".split(",")};
jQuery.each( srv.services, function(i, v) {
console.log( v );
});
Upvotes: 0
Reputation: 11481
it is not valid json array, your json data should be something like this:
var srv = {"services": ["26", "29"]};
..or of-cause you could split your string data using js split function:
jQuery.each(srv.services.split(","), function(i, v) {
console.log( v );
});
Upvotes: 1