【问题标题】:Error when loading jsrender templates through AJAX通过 AJAX 加载 jsrender 模板时出错
【发布时间】:2012-09-22 01:00:15
【问题描述】:

我正在尝试编写一个函数来加载外部文件中的模板并将它们与jsrender 一起使用。但是,我收到此错误:

TypeError: elem.getAttribute is not a function
[Break On This Error]   

value = $templates[elem.getAttribute(tmplAttr)];

我有一些 console.logs 显示模板是使用 ajax 检索的。

导致错误的基本代码如下:

var path    = 'templates/myTemplate.tmpl.html';
var data    = searchResultTeasers;
var target  = $('#results');

$.ajax({
    url     : path,
    aysnc   : false,
    success : function(template) {

        console.log("Path", path);
        console.log("Template", template);
        console.log("Data", data);

        //=============================================
        // Save Template with url as name for future
        //=============================================
        $.templates(path, template);

        //=============================================
        // Get Template String
        //=============================================
        var templateString  = $.templates(path);

        //=============================================
        // Render Template
        //=============================================
        renderedTemplate    = templateString.render(data);

        target.html(renderedTemplate);
    }
});

错误在 jsrender.js(第 829 行)中,我认为它与 $.templates(path); 但我不明白可能出了什么问题。

这里是项目压缩包的链接: http://sdrv.ms/QsZpQT

我的功能基于这篇文章: http://msdn.microsoft.com/en-us/magazine/hh975379.aspx

我不确定这是否与 jsRender 相关,但它仍然阻止我继续,我将不胜感激。

【问题讨论】:

  • 我建议您在这里解释您的问题,而不要求人们为您下载 ZIP 文件。人们对链接保持警惕。
  • 除非绝对必要(应该很少),你不应该在 ajax 调用上设置async: false(你也拼错了 async)。

标签: javascript ajax jsrender


【解决方案1】:

所以我自己也遇到了同样的错误(当尝试将外部模板与 jsrender 一起使用时,还需要加载本地文件(也就是说,我没有使用任何服务器端代码)。

不幸的是,您链接到的 MSDN 文章(在偶然发现之前,我最初阅读了该文章)和对 Store a jsRender template in a separate js file 的公认答案,都建议使用 $.get(),但您必须同时使用 $.ajax()对于 async 参数和 dataType 参数,如下所述。

这是我如何让它工作的:

  1. 使用了$.ajax()async: false(您在上面的示例中这样做了,只是您将“async”拼错为“aysnc”)。
  2. dataType: 'text' 参数设置为ajax 调用。这部分很关键——当我省略了 dataType 参数时,模板内容返回为 [object XMLDocument]$.templates 阻塞了。

所以最终运行的代码 sn-p 如下所示:

var file = 'views/my_template_file.html';
$.ajax({
    url: file,
    async: false,
    dataType: 'text',
    success: function(contents) {
        $.templates({my_template: contents});
        $('#myDiv').html(
            $.render.my_template()
        );
    }
});

希望这对其他人有所帮助。

【讨论】:

  • 您在回答的第 1 点中说要设置 async: true,但您的代码 sn-p 显示 async: false。我认为async: false 是正确的?谢谢。
【解决方案2】:

$.templates() 方法可能在引用的 msdn 文章编写后发生了变化。有没有看过Store a jsRender template in a separate js file

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-17
    • 2015-01-15
    • 2011-10-08
    • 1970-01-01
    相关资源
    最近更新 更多