0

我仍在忙于尝试将 JSON 文件设置为 HTML 网站。因此,如果 json 发生更改,则更改会动态加载到 HTML 中。到目前为止,我能够检索内容,甚至请求一些内容。但不是我想要的一切,因为来自 JSON 的标记有点奇怪。

由于跨站点保护,我无法直接发出 JSOP 请求,所以我用我在某处看到的一个小技巧解决了这个问题。我创建了一个简单的 test.php:

这样我就绕过了跨站点保护,一切正常。唯一的问题是我无法遍历我想要的所有数组。目前我正在使用以下脚本进行 JSOP 调用并获取数据。输出是一个很好的描述<li></li>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
</head>
<body>
    <ul id="episodes">
    </ul>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/mustache.js/0.7.0/mustache.min.js"></script>
    <script src="http://ps3scenefiles.com/json/handlebars.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script id="episodes-template" type="text/template">

            <li>{{description}}</li>

    </script>
    <script>
        $(function() {
            $.getJSON('http://ps3scenefiles.com/json/test.php', function(data) {
                var template = $('#episodes-template').html();
                var info = Mustache.to_html(template, data);
                $('#episodes').html(info);
            });
        });
    </script>
</body>
</html>

But when you open the link to the JSON (http://ps3scenefiles.com/json/test.php), you see that the Episodes array has another array with just numbers. How can i create a list like

Episode: 1 
     Id:13605 Active:true Lang:en Link: url
     Id:16525 Active:true Lang:ru Link: url
Episode: 2 
     Id:14854 Active:true Lang:en Link: url
     Id:19445 Active:true Lang:ru Link: url

So to be clear, how can i do a mustache (or handlebars) templating to make it look like the example?

4

1 回答 1

0

You can use Handlebars helper as mentioned in this answer

Here is a fiddle without styling, that prints out the data you expect (sort of, not all fields).

Here is the helper function -

Handlebars.registerHelper('eachkeys', function(context, options) {
  var fn = options.fn, inverse = options.inverse;
  var ret = "";

  var empty = true;
  for (key in context) { empty = false; break; }

  if (!empty) {
    for (key in context) {
        ret = ret + fn({ 'key': key, 'value': context[key]});
    }
  } else {
    ret = inverse(this);
  }
  return ret;
});
于 2013-03-30T05:06:26.717 回答