从json获取的json创建html

时间:2013-04-02 08:27:47

标签: php jquery ajax json symfony

我想做什么:

我有一个基于symfony2(php)的应用程序。一个简单的操作以json的形式返回数据

    $headers = array(
        'Content-Type' => 'application/json'
    );

    return new Response($data, 200, $headers);

这个动作是从像这样的javascript调用的。

function loadData(action){
    $.ajax({
        type: "POST",
        url: action,
        success: function(data){
            console.log(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });
}

到目前为止,这似乎非常基本。从控制台我可以看到返回的正确数据。这些数据应该放在项目网站的某个地方。

问题:

在javascript中有没有直接从json创建html的方法?实际上我想要从项目的逻辑中分离出模板(twig)。那么生成html是正确的,例如在loadData方法中成功回调?

我可以通过返回html而不是json来绕过这个问题。但我想为我的项目建立某种休息api,我认为这需要json用于运输。

有任何建议或想法吗?请分享您的处理方式。

3 个答案:

答案 0 :(得分:2)

您可以使用angular js。对于 symfony

有一件好事
angular.module('myApp', []).config(function($interpolateProvider){
        $interpolateProvider.startSymbol('[[').endSymbol(']]');
    };
);

使用{{更改[[并允许您在 TWIG 中使用模板。

This将有助于角度js中的 json查询

答案 1 :(得分:1)

获取数据并将其发送回服务器?我认为这不正确。

尝试使用收到的json对象查看underscore.js(_.template())在客户端进行模板化。

并试着像这样使用TWIG:

_.templateSettings = {
  interpolate : /\[\[(.+?)\]\]/g
};

var template = _.template("Hello [[ name ]]!");
template({name : "Mustache"});
=> "Hello Mustache!"

答案 2 :(得分:0)

看看Handlebars

您基本上可以将JSON传递给Handlebars模板:

模板:

<script id="entry-template" type="text/x-handlebars-template">
    <div class="entry">
        <h1>{{title}}</h1>
        <div class="body">
            {{body}}
        </div>
    </div>
</script>

JS:

var source   = $("#entry-template").html(),
    template = Handlebars.compile(source),
    context = {title: "My New Post", body: "This is my first post!"},
    html    = template(context);

结果:

<div class="entry">
    <h1>My New Post</h1>
    <div class="body">
        This is my first post!
    </div>
</div>