【问题标题】:loop through a json numeric array?循环一个json数字数组?
【发布时间】:2009-12-06 08:44:02
【问题描述】:

我使用 $.getJSON,这是我的 php 文件 echo:ing back jsonstring

for($i=1; $i<=10; $i++)
{
    $nr[] = "nr" . $i;
}

$nr = json_encode($nr);

echo "{'result': 'error', 'count': '$nr'}";

如何使用 jquery html() 循环所有 nr?

我想将它回显到网页,例如:

nr 1 编号 2 nr 3 编号 4 编号 5 编号 6 编号 7 编号 8 编号 9 nr 10

【问题讨论】:

    标签: jquery json


    【解决方案1】:

    在 jquery 中,评估“计数”,如

    array_data=eval(json_data["count"])
    

    php返回这个

    {'result': 'error', 'count': '["nr1","nr2","nr3","nr4","nr5","nr6","nr7","nr8","nr9","nr10"]'}
    

    一旦你评估“计数”

    array_data 将是["nr1","nr2","nr3","nr4","nr5","nr6","nr7","nr8","nr9","nr10"]

    之后你可以循环array_data

    【讨论】:

    • 如果count变量持有不同的字符串值怎么办?
    【解决方案2】:
    $.getJSON('file.php', function(data){
      for(var i=0; i<data.count.length; i++){
        alert(i+": "+data.count[i]);
      }
    });
    

    edit:问题在于你存储它的方式,php数组存储为json中的字符串。请尝试以下方法:

    for($i=1; $i<=10; $i++)
    {
        $nr[] = "nr" . $i;
    }
    $ json = array('result' => 'error', 'count' => $nr);
    echo json_encode($json);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-11
      • 2015-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-11
      • 1970-01-01
      相关资源
      最近更新 更多