【问题标题】:Filling and selecting a selectbox in mustache JS在 mustache JS 中填充和选择选择框
【发布时间】:2012-02-20 11:10:52
【问题描述】:

目前我有我的应用程序的“新项目表格”。我使用 mustacheJS 作为它的模板。有些字段需要来自数据库的数据,通过 ajax 发送。例如,某个选择框。

<select name="customerOrder">
    {{#order}} <option value="{{id}}">{{itemName}}</option> {{/order}}
</select>

用项目填充它的数据如下所示:

{
    "order": [
        {
            "id":1,
            "itemName":"Meat Lover's Pizza"
        }, //and so on...
    ]
}

在我即将创建编辑表单之前工作正常,除了用于填充选择框和复选框的表单数据之外,我现在必须将表单元素标记为选中。不过……

在另一个 ajax 调用中检索项目数据,因此是另一个 JSON 对象。我不一定要合并,因为数据可能具有不同的结构。我本可以尝试this approach 但这意味着表单数据和项目数据将是“一个” - 我不希望那样。我想要明确区分有形数据和无形数据

item 数据基本上是这样的,但可能嵌套在 JSON 对象的某个地方:

{
    "customer":"mario",
    "order": 1          --> this item i want selected in the form
    //and so on...
}

如果只有某种方式来构建表单,那么在仍然使用 mustache JS 的同时无缝地填充和标记它。我不想用相应的表单字段对数据进行硬编码。

我听说过运行时渲染和局部渲染,但我似乎不知道如何使用它们。

【问题讨论】:

    标签: javascript ajax json mustache


    【解决方案1】:

    我想通了!我从在胡子中使用“倒置部分”得到了这个想法。

    我在上面做的那个似乎是一个死胡同,或者如果我追求它,我会把一切都复杂化。

    我所做的是:

    1. 我没有让 ajax 发送 &lt;option&gt; 的值并在 &lt;select&gt; 中填充它们的模板,而是在服务器端构建了我的模板,并在 &lt;select&gt; 的选项中填充了数据。此外,我将模板用作所选项目的“标记”。

    2. 通过 ajax 获取的唯一内容是项目数据。我更改了 JSON 对象的结构以适应构建的模板。我没有交出数据,而是交出了“标记”

    最终结果:

    //build from the server-side ready with options, and with "markers
    
    <select name="customerOrder">
        <option value="1" {{#order}}{{#i1}}selected="selected"{{/i1}}{{/order}}>Meat Lover's Pizza</option>
        <option value="2" {{#order}}{{#i2}}selected="selected"{{/i2}}{{/order}}>Supreme</option>
    </select>
    
    //JSON "edit-mode" data
    
    {
        "order": {
            "i2":true // this will render the "selected" attribute on the one with "i2"
        }             // refer to "non-empty" list and "inverted sections"
    }                 // http://mustache.github.com/mustache.5.html
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-06
      • 2011-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多