最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery-tmpl - template function not working - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share asked Oct 24, 2010 at 13:28 dmnkhhndmnkhhn 1,0231 gold badge10 silver badges18 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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). 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)

  1. 暂无评论