通过ajax加载下划线模板丢失html,需要转义“<”,“>”

时间:2013-06-14 02:55:30

标签: javascript jquery ajax underscore.js

我正在使用ajaxify.js(https://github.com/browserstate/ajaxify/blob/master/ajaxify-html5.js)来加载页面内容。默认情况下,此脚本以异步方式从页面加载脚本,如下所示:

$scripts.each(function(){
    var $script = $(this), 
        scriptText = $script.text(),
        scriptType = $script.attr('type'),
        scriptId = $script.attr('id');

    scriptNode = document.createElement('script');

    if(scriptType) {
        $(scriptNode).attr('type', scriptType);
    }

    if(scriptId) {
        $(scriptNode).attr('id', scriptId);
    }

    scriptNode.appendChild(document.createTextNode(scriptText));
    contentNode.appendChild(scriptNode);
});

问题在于,使用我的下划线模板,使用$script.text()会完全忽略模板的HTML内容。

另一方面,使用$script.html()转义模板代码中的<>字符(下划线的<%等...),输出结束像:

&lt;% _.each(things,function(thing,key,list){ %&gt;

如何使脚本的内部html /文本保持原样,以便在AJAX加载时正常运行?谢谢!

完整的模板脚本是:

    <script type="text/html" id='furniture-template'>
        <div class="accordion collapse">
            <div class="accordion-group">
                <% _.each(things,function(thing,key,list){ %>

                <div class="accordion-heading">
                    <a class="no-ajaxy accordion-toggle ic-minus block collapsed" data-toggle="collapse" href="#things-<%= thing.slug %>">
                        <%= thing.title %>
                    </a>
                </div> <!-- header -->

                <div id="things-<%= thing.slug %>" class="accordion-body collapse">
                    <div class="accordion-inner">
                        <% for(var item in thing.items) { %>
                        <div class="item">
                            <% if( thing.items[item].images == true ) { %>
                                <a class="no-ajaxy" data-target="<%= thing.items[item].slug %>-gal" class="img-link ic-cam fl" title="View an example"></a>
                            <% } %>

                            <a 
                                class="item-add ic-plus" 
                                data-title="<%= thing.items[item].title %>" 
                                data-slug="<%= thing.items[item].slug %>"
                                data-img="<%= thing.items[item].images %>"
                                data-shorthand="<%= thing.items[item].shorthand %>"
                                data-price="<%= thing.items[item].price %>"
                            >
                                <%= thing.items[item].title %>
                            </a>
                        </div>
                        <% } %>
                    </div> <!-- inner -->
                </div> <!-- accordion-body -->

            <% }); %>
            </div>
        </div>
    </script>

2 个答案:

答案 0 :(得分:1)

好奇的情况。简单的解决方案是使用.html()和unescape转义的下划线序列,这可能是你想要的(也就是说你可能不想忘记一切):

$script.html().replace(/&lt;%/gi, '<%').replace(/%&gt;/gi, '%>')

答案 1 :(得分:0)

你没试过这个:

contentNode.innerHTML = scriptnode;