2

我正在构建一个小页面,它使用 jquery 的 getJSON 调用 API,然后使用 mustache 模板呈现数据(至少这是计划)。但是,我的 JSON 没有节点根,并且无法使用正确的小胡子机制遍历 JSON 响应数据。

//start
file : jsonresponse.jsonp

?([{"CountryIsoAlpha3Code":"AFG","CountryName":"Afghanistan"},
{"CountryIsoAlpha3Code":"ALA","CountryName":"Åland Islands"},
{"CountryIsoAlpha3Code":"ALB","CountryName":"Albania"}])
//end

//start
file: tmpl.mustache

<option value="{{CountryIsoAlpha3Code}}">{{CountryName}}</option>
//end

//start
file: render.js

$.getJSON(jsonresponse.jsonp, function(data) { 
   var tpl = tmpl.mustache,
   i=data.length,
   html = '';
     while(i--){
       html = html + mustache.render(tpl, data[i]);
     }

//end

我意识到这是完全错误的(仅在模板使用中,假设我实际上正确地传递了数据和模板)但它确实有效。但是,如果我想执行以下操作怎么办……我该怎么做!?:

//start
//file : daydreamer.mustache

<h1>This title is only awesome when it's rendered once</h1>
{{#}}  //no root node attempt at recursive templating rendering
     <option value="{{CountryIsoAlpha3Code}}">{{CountryName}}</option>
{{/}}

//end  

如果不清楚,请告诉我,我知道一个糟糕的问题是眼睛疼。我会尽快编辑。谢谢。

4

1 回答 1

5

根据您在此应用程序/用例上控制的部分,您有 2 个可能的修复:修改 JSON 数据以包含此类根节点,或者将该根节点添加到您的数据中。

对于两种解决方案,必须对 mustache 模板进行如下修改:

{{#options}}
    <option value="{{CountryIsoAlpha3Code}}">{{CountryName}}</option>
{{/options}}

现在您可以直接在服务器上在您的终端上包装数据,然后getJSON对于第二个解决方案的调用将是这样的(对于第一个解决方案,将{options: data}包装器替换为 just data)。我将使用第二个假设您无法控制服务器端,因为该 API 是由其他人固定/授权的:

$.getJSON("jsonresponse.jsonp", function(data) { 
    var tpl = tmpl.mustache,
        html = '';

    html = mustache.render(tpl, {options: data});
}
于 2012-11-21T00:02:41.237 回答