【问题标题】:How to parse nested jsonp objects using javascript?如何使用 javascript 解析嵌套的 jsonp 对象?
【发布时间】:2016-10-04 22:22:09
【问题描述】:

我有一个有效的 jsonp 如下。我正在尝试解析它,但我不知道如何访问视频元素!谁能告诉我如何在 for 循环中引用这些元素(来源、拇指、标题)?谢谢

有效的 jsonp:

{
    "categories": [{
        "name": "october list",
        "videos": [{
                "sources": [
                    "http://www.somesite.com.com/test.m3u8"
                ],
                "thumb": "http://www.somesite.com.com/1.jpg",
                "title": "title of test",
                "subtitle": "",
                "description": ""
            }, {
                "sources": [
                    "http://www.somesite.com/test2.m3u8"
                ],
                "thumb": "http://www.somesite.com/2.jpg",
                "title": "test2",
                "subtitle": "",
                "description": ""
            }

        ]
    }]
}

javascript:

 $.get("http://www.someapisite.com/test.php",
        {

          dataType: "jsonp"
        },

        function(data,status){

 var json = $.parseJSON(data);

// then loop the single items
    for(i in json)
    {
       // create HTML code
       var div = "<div class=\"image\">\n" + 
       "<a href=\"javascript:dofunction('./test.php?title=" + json[i].title + "&TargetUrl=http://somesite.com/" + json[i].sources + "')\">\n" +
       "<img src=\""+ json[i].thumb +"\" alt=\"..\" />\n" +
       "</a>\n" +
       "</div>\n";
       // append it inside <body> tag.
         $("#myDiv").append(div);
    }

        });

【问题讨论】:

  • 那是不是 JSONP。
  • 您不必致电$.parseJSON$.ajax/$.get/$.getJSON 已经为你做到了(如果是实际的 JSONP,你永远看不到字符串)
  • 感谢您的回复。 @Bergi 在删除 parseJson 并改用数据后,我仍然没有在 div 中获取任何数据!如何解决?

标签: javascript jquery json parsing jsonp


【解决方案1】:

您似乎想要遍历每个类别的视频数组。

使用 javascript forEach

json.categories.forEach(function(category, index, array) {
category.videos.forEach(function(videoDetail, index, array) {
    <img src=\"" videoDetail.thumb \"" />
    <h3>videoDetail.title</h3>
 });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多