开发者

jquery-tmpl - template function not working

The following code:

jQuery(document).ready(function($) {
    function getBooks() {
        var query =开发者_开发百科 "ajax.php?do=allbooks";
            $.ajax({
                dataType: "jsonp",
                url: query,
                jsonp: "callback",
                success: showBooks
            });
    }

    function showBooks(data) {
    $("#bookTmpl").tmpl(data, { 
        getName: function() {
          return 'bla';
        }
    }).appendTo( "#test" ); 
    }

    getBooks();
});

What I am trying to do is use the getName()-function in my template.

Let's pretend my template looks like this:

<script id="bookTmpl" type="text/x-jquery-tmpl">
    <li>
    ${title} by ${author}<br />
    Rating: ${rating} -> ${getName()}
    </li>
</script>

What do I have to change to make it work? Right now, the function isn't even executed. Everything else works.


You just need to adjust the call a bit, change this:

${getName()}

To this:

${this.getName()}

You can test it out here.


Try attaching the error: fn callback in $.ajax and see what might be wrong. Perhaps the JSON is malformed (you can check that with jsonlint.org). If the success: fn isn't even being called, something is wrong (404, JSON parse error etc.).

Also, JSONP might be a bit overkill if you're requesting JSON from the same domain (e.g. try something like $.getJSON or dataType: 'json')

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜