简体   繁体   English

从 javascript 文件中剔除 js 模板

[英]knockout js template from javascript file

I'm submitting a form to a php file, which returns some products from the database.我正在向一个 php 文件提交一个表单,该文件从数据库中返回一些产品。 I now need to add a knockout template with the returned data.我现在需要使用返回的数据添加一个淘汰赛模板。 Here is the code:这是代码:

$("#search-filter-form").submit(function(event) {
        // stop form from submitting normally 
        event.preventDefault();

        // get some values from elements on the page: 
        var $form = $( this ),
            url = $form.attr( 'action' );

        // Send the data using post 
        var posting = $.post(url, 
            {   place: searchFilterViewModel.searchFilterAutoComplete.placeObject,
                categories: searchFilterViewModel.categorySelect.selectedCategories
            }).done(function(data) {
                searchResultsViewModel.allProducts(JSON.parse(data));
                for(var x = 0; x < searchResultsViewModel.allProducts().length; x++) {
                    $("search-results").append();// NEED TO APPEND THE KNOCKOUT TEMPLATE HERE
                }
            });
    });

I want to have a seperate file with the html template.我想要一个带有 html 模板的单独文件。 I have created this example file:我创建了这个示例文件:

product_template.html: product_template.html:

<script type="text/html" id="product-template">
    <h3 data-bind="text: allProducts.name"></h3>
    <p>Credits: <span data-bind="text: credits"></span></p>
</script>

How do I get that template file to print out, from within the javascript function above?如何从上面的 javascript 函数中打印出该模板文件?

Store the data in an observable/object, and pass that to the template itself, so it can read it.将数据存储在 observable/object 中,并将其传递给模板本身,以便它可以读取它。

You only linked the template file, you need another line to apply data to it, eg您只链接了模板文件,您需要另一行将数据应用于它,例如

<div data-bind="template: { name: 'product-template', data: buyer }"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM