简体   繁体   English

jQuery.each-如何遍历JSON对象元素?

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

i am very new to play with JSON. 我是玩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. 我需要遍历来自AJAX的JSON响应,实际上,我是从db表中以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. 如果在FF控制台区域中运行以下代码,您会发现它正在针对每个数字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 :) 谢谢 :)

srv.services is a string of comma separated values, so $.each() won't work correctly. srv.services是由逗号分隔的值的字符串,因此$.each()无法正常工作。 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/ 工作演示: http : //jsfiddle.net/AndyE/veP4p/

You could also have your JSON service return an array instead of a string, eg {"services":[26, 29]} . 您还可以让JSON服务返回一个数组而不是一个字符串,例如{"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. 如果您使用正确的JSON兼容方法进行编码并且数据是数组,则将在服务器上自动为您完成此操作。

it is not valid json array, your json data should be something like this: 它不是有效的json数组,您的json数据应如下所示:

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

..or of-cause you could split your string data using js split function: ..或原因是,您可以使用js split函数拆分字符串数据:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM