Error when loading jsrender templates through AJAX

那年仲夏 提交于 2019-12-06 04:43:25
Dmitri Zagidulin

So I just ran into this same error, myself (when trying to use external templates with jsrender, with the additional requirement of loading local files (meaning, I'm not using any server-side code)).

Unfortunately the MSDN article you link to (and that I went to initially, before stumbling onto this) and the accepted answer to Store a jsRender template in a separate js file, both recommend to use a $.get(), but you have to use $.ajax() both for the async parameter, and the dataType parameter, as explained below.

Here's how I got it to work:

  1. Used $.ajax() and async: false (which you did in the example above, except you misspelled 'async' as 'aysnc').
  2. Set the dataType: 'text' parameter to the ajax call. This part was key -- when I left out the dataType parm, the template contents returned as an [object XMLDocument], which $.templates choked on.

So the final code snippet that ended up working looks like this:

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()
        );
    }
});

Hope this helps somebody else down the line.

Fuwjax

It's possible that the $.templates() method has changed since the referenced msdn article was written. Have you already looked at Store a jsRender template in a separate js file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!