Javascript 在mustache JS中填充和选择选择选择框

Javascript 在mustache JS中填充和选择选择选择框,javascript,ajax,json,mustache,Javascript,Ajax,Json,Mustache,目前我有“新项目表”供我申请。我使用mustacheJS作为它的模板。有些字段需要通过ajax从数据库发送数据。例如,某个选择框 <select name="customerOrder"> {{#order}} <option value="{{id}}">{{itemName}}</option> {{/order}} </select> 工作正常,直到我准备创建编辑表单,其中,除了填写选择框和复选框的表单数据外,我现在必须将表单元素标

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

<select name="customerOrder">
    {{#order}} <option value="{{id}}">{{itemName}}</option> {{/order}}
</select>
工作正常,直到我准备创建编辑表单,其中,除了填写选择框和复选框的表单数据外,我现在必须将表单元素标记为选中。然而

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

项目数据基本上如下所示,但可能嵌套在JSON对象中的某个位置:

{
    "customer":"mario",
    "order": 1          --> this item i want selected in the form
    //and so on...
}
如果只有某种方法来构建表单,那么在那之后,在仍然使用MustacheJS的情况下无缝地填充和标记表单。我不想用相应的表单字段硬编码数据


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

我明白了!我是通过在胡子上使用“倒立部分”得到这个想法的

我在上面做的那件事看起来像是一条死胡同,或者如果我继续做下去,我会把一切都复杂化

我所做的是:

  • 我没有让ajax发送
    的值并在
    中填充它们,而是让我的模板构建在服务器端,用数据填充
    的选项。此外,我使用模板作为所选项目的“标记”

  • 通过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
    
    //使用选项和“标记”从服务器端构建
    肉食爱好者比萨饼
    最高的
    //JSON“编辑模式”数据
    {
    “命令”:{
    “i2”:true//这将在带有“i2”的属性上呈现“selected”属性
    }//参考“非空”列表和“反向部分”
    }                 // http://mustache.github.com/mustache.5.html
    
    //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