javascript - JSON 数组 - 显示数据所需的帮助

标签 javascript jquery html json jsonp

{
"entries": [
    {
        "id": 23931763,
        "url": "http://www.dailymile.com/entries/23931763",
        "at": "2013-07-15T21:05:39Z",
        "message": "I ran 3 miles and walked 2 miles today.",
        "comments": [],
        "likes": [],
        "user": {
            "username": "DeanaLaughli",
            "display_name": "Deana O.",
            "photo_url": "http://s3.dmimg.com/pictures/users/361413/1329826045_avatar.jpg",
            "url": "http://www.dailymile.com/people/DeanaLaughli"
        },
        "workout": {
            "activity_type": "Fitness",
            "distance": {
                "value": 5,
                "units": "miles"
            },
            "felt": "great"
        }
    },
    {
        "id": 23931680,
        "url": "http://www.dailymile.com/entries/23931680",
        "at": "2013-07-15T21:01:03Z",
        "message": "More strength training",
        "comments": [],
        "likes": [],
        "location": {
            "name": "MA"
        },
        "user": {
            "username": "Ecm2571",
            "display_name": "Eileen",
            "photo_url": "http://s3.dmimg.com/pictures/users/323833/1368556483_avatar.jpg",
            "url": "http://www.dailymile.com/people/Ecm2571"
        },
        "workout": {
            "activity_type": "Weights",
            "title": "Upper and lower body "
        }
    }
]
}

这是我通过 URL 的 JSONP 请求获取的 JSON 数组的示例。我正在尝试显示:

  • 照片_url
  • 用户名
  • 消息
  • 地点.名称
  • 锻炼.activity_type
  • 锻炼持续时间
  • 锻炼.距离.值
  • 锻炼.距离.单位

但是,正如您在数组中看到的那样,有时不会给出此信息,并且当发生这种情况时,代码将停止加载更多条目。我需要一种在没有要加载的数据时显示空白的方法。这是我的代码,感谢您的帮助。

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
<script>

$(function() {

var entries = [];
var workout.activity
var dmJSON = "http://api.dailymile.com/entries.json?callback=?";
$.getJSON( dmJSON, function(data) {
$.each(data.entries, function(i, f) {
  var tblRow =      "<tr>" + 
            "<td><img src=" + f.user.photo_url + "></td>" +
            "<td>" + f.user.username + "</td>" + 
            "<td>" + f.message + "</td>" + 
            //"<td>" + f.location.name + "</td>" +
            "<td>" + f.workout.activity_type + "</td>" +
            "<td>" + f.workout.duration + "</td>" +
            "<td>" + f.workout.distance.value + f.workout.distance.units + "</td>" +
            "</tr>"
   $(tblRow).appendTo("#entrydata tbody");
});

});

});
</script>
</head>

<body>

<div class="wrapper">
<div class="profile">
<table id= "entrydata" border="1">
<thead>
        <th></th>
        <th>Username</th>
        <th>Message</th>
    <th>Exercise Type</th>
    <th>Duration</th>
    <th>Distance</th>
    </thead>
  <tbody>

   </tbody>
</table>

</div>
</div>

</body>

</html>

最佳答案

首先在 Chrome 中运行它并打开网络工具。 一旦出现“到达”错误,您将在控制台日志中看到该错误。

您的问题是您尝试读取未定义的值。 您可以通过在尝试从每个对象读取任何值之前检查每个对象或使用在值丢失时返回默认值的函数来解决此问题。

这是一个完整的工作代码:

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
    <script>

        /**
         * Extract the property formthe object.
         * If teh property not found it will return empty string
         */
        function getProperty(object, property) {

            if (!property) {
                return '';
            }

            var
            // Break the property to its nested properties
                    properties = property && property.split('.'),
            // the current object that we want to extract the property from
                    current = object,
                    index;

            // Loop over the properties and process them
            for (index = 0; index < properties.length; index++) {
                property = properties[index];
                // Check to see that there is a property with the given name
                if (current.hasOwnProperty(property)) {
                    current = current[property];
                } else {
                    return '... N/A ...';
                }
            }

            // If we got so far it means the the 'current' contain the needed value
            return current;
        }

        $(function () {

            var entries = [],
                    dmJSON = "http://api.dailymile.com/entries.json?callback=?";

            $.getJSON(dmJSON, function (data) {
                $.each(data.entries, function (i, f) {
                    var tblRow = "<tr>" +
                            "<td><img src=" + getProperty(f, 'user.photo_url') + "></td>" +
                            "<td>" + getProperty(f, 'user.username') + "</td>" +
                            "<td>" + getProperty(f, 'message') + "</td>" +
                        //"<td>" + f.location.name + "</td>" +
                            "<td>" + getProperty(f, 'workout.activity_type') + "</td>" +
                            "<td>" + getProperty(f, 'workout.duration') + "</td>" +
                            "<td>" + getProperty(f, 'workout.distance.value') + getProperty(f, 'workout.distance.units') + "</td>" +
                            "</tr>";

                    $(tblRow).appendTo("#entrydata tbody");
                });

            });

        });
    </script>
</head>

<body>

<div class="wrapper">
    <div class="profile">
        <table id="entrydata" border="1">
            <thead>
            <th></th>
            <th>Username</th>
            <th>Message</th>
            <th>Exercise Type</th>
            <th>Duration</th>
            <th>Distance</th>
            </thead>
            <tbody>

            </tbody>
        </table>

    </div>
</div>

</body>

</html>

关于javascript - JSON 数组 - 显示数据所需的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17664775/

相关文章:

html - 如何修复主页网站上的主要部分?将附上链接

javascript - 更改 HTML 字符串中的图像源属性并再次返回 HTML 字符串

javascript - 输入可以限制为html &lt;textarea&gt;吗?

javascript - 对象字面值和 React.js

javascript - D3负值条形图

javascript - 选中所有复选框

html - 关于晦涩难懂的希腊字符的 Unicode/HTML 问题

javascript - 比较两个不同的数组元素删除node js中的匹配元素

jquery根据特定列的值突出显示行

javascript - Backbone 项目适用于除 Firefox 之外的所有浏览器