php - 使用 jquery 遍历 json 数组

标签 php jquery json

有一些帖子与我类似的问题:How do I iterate over a JSON array using jQuery/AJAX call from PHP?但不完全相同。

我从 jquery 得到错误信息: a 为空

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

$(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 格式):

$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 格式的数据:

[
    {
        "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 is null”错误就消失了。我做错了什么?

最佳答案

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

错误在别处。

编辑:

试试这个来帮助调试。

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

xhr 将包含很多关于正在发出的请求的信息。响应文本包含什么?什么是状态文本?

关于php - 使用 jquery 遍历 json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8329495/

相关文章:

php - 提交按钮和 document.Form.submit() 不同的脚本进行处理

php - php中 session 变量中的输入字段值

javascript - 如何使用 AJAX 对选择选项执行 PHP 查询?

jQuery 动画滚动

java - 如何为父类和子类使用单独的自定义 json 序列化程序?

json - 为 karma 单元测试获取 json 文件

php - 使用 PDO 发送空值会导致错误

php - 更改单个页面的链接颜色

jquery - 在 jQuery Mobile 中垂直居中 DIV 的内容

php - Javascript JSON.parse 响应文本 "Unexpected end of input"