简体   繁体   中英

How to Render Data from server with backbone.js

First for information, that is my response from server

$response = array();
            $i = 0;
            while($result = mysql_fetch_assoc($query)){
                $response[$i]["id"]             = $result["ID"];
                $response[$i]["post_date"]      = $result["post_date"];
                $response[$i]["post_content"]   = $result["post_content"];
                $response[$i]["nickname"]       = $result["nickname"];
                $i++;
            }
            echo json_encode($response);

it seems that @k33g_org way does work but now console say me Uncaught ReferenceError: nickname is not defined

my template is

<script type="text/template" id="tplhome_post_list">
            <div class="post">
                <div class="view">
                    <p class="header_post">
                        <%= nickname %> - Le <%= post_date %>
                    </p>
                    <div class="statut">
                        <div class="like">
                            8
                        </div>
                        <div class="reply">
                            25
                        </div>                          
                    </div>
                    <p class="clear">
                        <%= post_content %>
                    </p>
                </div>
            </div>
        </script>

how can fix it ?? define template value ??

you have to write fetch like this :

Posts.fetch({
    success:function(data) {
       /* when you get data from server request data variable is populated */
       /* then you can call render() method of the view */
    }, 
    error : function(err) { 
      throw "Houston we've got a problem...";
    }
});

You can pass data to render method (something like this)

    render : function(data) {
        var renderedContent = this.template(this.data.toJSON());
        $(this.el).html(renderedContent);
        return this;
    }

Or, better, you can bind reset event of the collection to the view, in the initialize method of the view, put this :

_.bindAll(this, 'render');
this.collection.bind('change', this.render);
this.collection.bind('add', this.render);
this.collection.bind('remove', this.render);

then when collection content change (ie when fetching), render() is called

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM