使用jquery遍历json数组 [英] Iterate over json array using jquery

查看:86
本文介绍了使用jquery遍历json数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有些帖子也有类似的问题:

There have been some post with my similar problem: How do I iterate over a JSON array using jQuery/AJAX call from PHP? but not quite the same.

我从jquery中得到错误: a为空

I'm getting and error from jquery: a is null

这是因为我添加了循环遍历json数据的代码:

It is because of the code I've added to loop through the json data:

$(function () 
{
$.ajax({                                      
  url: 'ajax_dashboard/api.php',    //the script to call to get data          
  data: "",                        
  dataType: 'json',                    
  success: function(data)          
  {
        $.each(data, function() {
          $.each(this, function(k, v) {
                $('#output').append("<b>key: </b>"+k+"<b> value: </b>"+v)
                    .append("<hr />");
          });
        }); 
  } 
});
}); 

这是php文件(我确实验证了给出的有效JSON格式):

And here is the php file (which I did verify gives valid JSON format):

$query_camera_name = "SELECT camera_name, camera_status, camera_quality, email_notice, camera_hash, camera_type FROM #__cameras WHERE user_id=".$user->id." AND camera_status!='DELETED'";
$db->setQuery($query_camera_name);
//get number of cameras so we can build the table accordingly
$db->query();
$num_rows = $db->getNumRows();
// We can use array names with loadAssocList.
$result_cameras = $db->loadAssocList();
echo json_encode($result_cameras);
?>

这将返回此json格式的数据:

This returns this json formatted data:

[
    {
        "camera_name": "ffgg",
        "camera_status": "DISABLED",
        "camera_quality": "MEDIUM",
        "email_notice": "DISABLED",
        "camera_hash": "0d5a57cb75608202e64b834efd6a4667a71f6dee",
        "camera_type": "WEBCAM"
    },
    {
        "camera_name": "test",
        "camera_status": "ENABLED",
        "camera_quality": "HIGH",
        "email_notice": "ENABLED",
        "camera_hash": "6ab000ef7926b4a182f0f864a0d443fc19a29fdd",
        "camera_type": "WEBCAM"
    }
]

如果我删除循环,则"a为null"错误消失了.我在做什么错了?

If I remove the loops the "a is null" error is gone. What am I doing wrong?

推荐答案

您的迭代代码可以正常工作: http://jsfiddle.net/SuyMj/

Your iteration code works just fine: http://jsfiddle.net/SuyMj/

该错误在其他地方.

尝试此操作以帮助调试.

Try this to help debug.

success: function(data, textStatus, xhr) {
  console.log(xhr);
  ...
}

xhr将包含有关正在发出的请求的许多信息. responseText包含什么?什么是statusText?

xhr will contain a lot of information about the request being made. What does the responseText contain? What is the statusText?

这篇关于使用jquery遍历json数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆