2011-03-17 42 views
6

我在我的新网站中使用JSON和MUSTACHE模板。但我不知道如何从json数据中获取HTML。我在后端使用PHP,作为API提供者。我对这个概念很陌生。艾维的帮助和建议是受欢迎的。如何从JSON数据中获取HTML,使用MUSTACHE?

谢谢。

代码我使用::

<script> 
// this is for base 
    this.get(/\#\/(.*)/, function(){ 
     var send_url = '<?php echo $url?>sammy/' + this.params['splat']; 
     var context = this; 
     $.getJSON(send_url, function(data) { 
     var template = data.template; 
     context.renderEach('<?php echo $url?>mustache_templates/' + template + '', data.data).swap(); 
     }); 
    }); 
</script> 

JSON数据就像是::

{"menu": { 
    "id": "file", 
    "string": "<a href=\"http:\/\/stackoverflow.com\/questions\/5335873\/how-to-get-html-from-json-data-using-mustache#xyz\">string</a>", 
}} 

胡子模板:

{{#string}} 
<div> 
{{string}} 
</div> 
{{/string}} 

电流输出:

<a href="https://stackoverflow.com/questions/5335873/how-to-get-html-from-json-data-using-mustache#xyz">string</a> 

输出需要:

string

感谢您

回答

11

电流输出:

<a href="http://stackoverflow.com/questions/5335873/how-to-get-html-from-json-data-using-mustache#xyz">string</a> 

这不是输出。你实际得到的是类似于

&lt;a href=&quot;http://stackoverflow.com/questions/5335873/how-to-get-html-from-json-data-using-mustache#xyz&quot;&gt;string&lt;/a&gt; 

这当然看起来像你在浏览器中发布的内容。小胡子HTML默认情况下会转义所有变量,所以它们不会弄乱您的HTML。

在这种情况下,您不希望这样,所以您应该在模板中使用{{{string}}}。请务必只使用受信任的变量来完成此操作,切勿使用它来输出任何用户输入。

0

看看在PHP json_decode,那你拿你的数据,你(我相信)的阵列可以养活你的模板发动机:

$json = <<< EOJ 
{"menu": { 
    "id": "file", 
    "string": "<a href=\"http:\/\/stackoverflow.com\/questions\/5335873\/how-to-get-html-from-json-data-using-mustache#xyz\">string</a>", 
}} 
EOJ; 

$json_parsed = json_decode($json_raw, TRUE); // return an array, not an object 

DoYourMustacheThingWith($json_parsed); 
+0

我很抱歉,我认为我无法解释它很好,实际上我没有将值传递给PHP,但从中获得价值..我编辑了问题以更好地理解..感谢您的回复。期待更多的帮助 – 2011-03-17 08:20:12