最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

i am very new to play with JSON. I need to iterate over JSON response ing 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 :)

i am very new to play with JSON. I need to iterate over JSON response ing 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 :)

Share Improve this question edited Nov 23, 2010 at 11:39 Fawaz Qamar asked Nov 22, 2010 at 13:27 Fawaz QamarFawaz Qamar 711 silver badge9 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 7

srv.services is a string of ma 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/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-pliant 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)

  1. 暂无评论