2016-10-04 34 views
0

我有一個有效的jsonp如下。我試圖解析它,但我不知道如何訪問視頻元素!可以在任何一個可以告訴我如何引用裏面的那些元素(源,拇指,標題)for循環感謝如何使用javascript解析嵌套的jsonp對象?

有效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); 
    } 

     }); 
+0

即*不* JSONP。 – Bergi

+0

您不必調用'$ .parseJSON'。 '$ .ajax' /'$ .get' /'$ .getJSON'已經爲你做了這件事(並且在實際的JSONP的情況下,你永遠不會看到一個字符串) – Bergi

+0

可能的[Access/process(nested)對象,數組或JSON](http://stackoverflow.com/q/11922383/1048572)? – Bergi

回答

0

看來你想要遍歷每個類別的視頻數組。

使用JavaScript的forEach

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