【问题标题】:Loading mustache template in jQuery returns Document object instead of raw string在 jQuery 中加载 mustache 模板返回 Document 对象而不是原始字符串
【发布时间】:2011-12-22 22:33:33
【问题描述】:

我正在使用 icanhaz.js 和 mustache 加载模板,我正在使用以下方法按需加载 mustache 模板:

loadTemplate: function(name, callback) {
            if (!ich.templates[name+"_template"]) {
                jQuery.get("/js/templates/"+name+".mustache", function(data) {
                  window.ich.addTemplate(name+"_template", data);
                  callback();
                });
             } else {
                callback();
             }
        }

检查在调试器中返回的数据变量,但是,有时返回的是一个 Document 对象,而不是我可以使用的原始字符串。我有时会说,因为如果模板文件中的 html 在文件顶部没有嵌套的 DOM 元素,则模板会根据需要加载。这是一种非常奇怪的行为,我希望得到一些帮助来解释。

所以,例如模板文件:

<div>
     <div>My name is {{name}}</div>
</div>

加载时会作为 Document 对象返回。

然而,这个模板文件:

 <div></div>
 <div>
     <div>My name is {{name}}</div>
 </div>

根据需要作为原始字符串返回。

我不知道为什么让没有任何子级的顶级 div 会对被标识为 Document 的模板与字符串产生影响。有什么想法吗?

【问题讨论】:

    标签: jquery lazy-loading mustache icanhaz.js


    【解决方案1】:

    由于您没有向$.get() 提供dataType 参数,因此您在“智能猜测”模式下运行。 related documentation 说:

    如果没有指定,jQuery 将尝试根据 MIME 推断它 响应的类型(XML MIME 类型将产生 XML,在 1.4 JSON 将产生一个 JavaScript 对象,在 1.4 script 将执行脚本, 其他任何内容都将作为字符串返回)。

    因此,您的服务器可能会将某些模板发送为text/html(或text/plain),而将其他模板发送为text/xml。检查响应标头(使用 Fiddler 或等效工具)以检查是否确实如此会很有趣。

    顺便说一句,指定请求的数据类型应该可以完全解决这个问题:

    jQuery.get("/js/templates/" + name + ".mustache", function(data) {
        window.ich.addTemplate(name + "_template", data);
        callback();
    }, "html");      // Always return HTML as plain text.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-18
      • 2011-07-29
      • 2012-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多