开发者

jQuery.each - How to iterate over JSON objects element?

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 = 开发者_如何学JAVA{"services":"26,29"};

jQuery.each( srv.services, function(i, v) {
    console.log( v );
});

Any help would be appreciated. THanks :)


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.


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 );
});


Not sure this is an answer to your problem but given the declaration from above, try splitting on , before iterating:

var srv = {"services":"26,29"};

jQuery.each( srv.services.split(','), function(i, v) {
    console.log( v );
});

(Demo)


You have to create an array first

var srv = {"services":"26,29".split(",")};

jQuery.each( srv.services, function(i, v) {
    console.log( v );
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜