模板化AJAX返回数据

时间:2013-12-15 11:18:50

标签: php html ajax templates mustache

我正在通过obj上的表单从php接收数据,并通过胡子模板发送它来制作表格。

我的问题是如何控制数据的换行符,我希望插入<tr&gt;对于每3 <td>,这可能没有Javascript的帮助吗?

来自PHP的数据:

    {"Form":[
{"Label":"Name","Info":"megan fox"},
{"Label":"Phone","Info":"(111) 222-3333"},
{"Label":"Name","Info":"sfsdfsdf"},
{"Label":"Zip","Info":"dsfsdfs"},
{"Label":"State","Info":"sdfsf"},
{"Label":"City","Info":"4fsfsf"},
{"Label":"Address","Info":"dfsodufsf"},
{"Label":"Phone #","Info":"(111) 222-3333"},
{"Label":"Zip","Info":"34545345"},
{"Label":"State","Info":"sdfsf"},
{"Label":"City","Info":"sdfosdffd"},
{"Label":"Address","Info":"sdfsfssf"}
    ]}

小胡子模板

<table>
{{#Form}}
<tr>
<td><span class="label">{{Label}}</span>
<span class="Information">{{Info}}</span> 
</td>
</tr>
{{/Form}}
</table>

结果

<table>
<tbody>
<tr>
<td><span class="label">Name</span> 
<span class="Information">megan fox</span> </td>
</tr>
<tr>
<td><span class="label">Phone</span> 
<span class="Information">(434) 434-543</span> </td>
</tr>
<tr>
<td><span class="label">Name</span> 
<span class="Information">sfsdfsdf</span> </td>
</tr>
   ..
</tbody>
</table>

我想要的:1 TR中的3 TD。

<table>
<tbody><tr>
<td><span class="label">Name</span> 
<span class="Information">megan fox</span> </td>
<td><span class="label">Phone</span> 
<span class="Information">(111) 222-3333</span> </td>
<td><span class="label">Name</span> 
<span class="Information">sfsdfsdf</span> </td>
</tr>
...
</tbody></table>

1 个答案:

答案 0 :(得分:1)

在这里阅读手册http://mustache.github.io/mustache.5.html就是说

  

当值为非空列表时,块中的文本将为   为列表中的每个项目显示一次。块的上下文   将被设置为每次迭代的当前项。通过这种方式,我们可以   循环收集。

我认为如果您可以更改服务器的输出,这可能是最简单的解决方案。你能把输出看起来像这样吗?

{
    "Form": {
        "Items": [
            {"Label": "Name", "Info": "megan fox"},
            {"Label": "Phone", "Info": "(111) 222-3333"},
            {"Label": "Name", "Info": "sfsdfsdf"},
            {"Label": "Zip", "Info": "dsfsdfs"},
            {"Label": "State", "Info": "sdfsf"},
            {"Label": "City", "Info": "4fsfsf"},
            {"Label": "Address", "Info": "dfsodufsf"},
            {"Label": "Phone #", "Info": "(111) 222-3333"},
            {"Label": "Zip", "Info": "34545345"},
            {"Label": "State", "Info": "sdfsf"},
            {"Label": "City", "Info": "sdfosdffd"},
            {"Label": "Address", "Info": "sdfsfssf"}
        ]
    }
}

如果是这样,您可以让模板迭代项目,然后您需要将模板更改为此;

<table>
{{#Form}}
<tr>
{{#Items}}
<td><span class="label">{{Label}}</span>
<span class="Information">{{Info}}</span> 
</td>
{{/Items}}
</tr>
{{/Form}}
</table>