需要 table 来填充搜索栏中的搜索结果

Need table to populate with search results from search bar

我有一个带有搜索栏和一堆下拉菜单的网页,但现在只有搜索栏很重要。无论如何,当我单击搜索栏后的转到按钮时,它会显示 table,但不会像我想的那样将搜索到的项目放在 table 中。我通过 Python

使用 SimpleHTTPServer
<form role="form" id="form">
        <fieldset>
            <div class="form-group">
            <div class="row">
            <label for="search"> </label>
            <div class="col-lg-7 col-lg-offset-2">
            <input type="text"
                class="form-control" name="search" id="search"
                placeholder="Search for..." />
            </div>

                <div class="col-lg-2">
                <br>
                <button type="button" class="btn btn-success" id="submit">       Go!
                </button> </div> </div> </div>
            </fieldset>
    </form> 

JS: $('#submit').click(函数(e){ e.preventDefault();

         var search=$('#search').val();
         $.get('post2.html', function(returndata){

         $('#output').html(returndata);

         } );


    });

<table class="table">
    <thead>
        <tr>
        <th> Previous Searches: </th>
        </tr>
    </thead>

        <tr>
        <script>document.write(search)</script>
        </tr>

</table>

您的 "search" 超出范围。它仅存在于 .click() 的匿名函数中。您需要以某种方式将 "search" 传递到您的 HTML 中,但这在您当前的设置中是不可能的。

我建议使用类似 Handlebars 的工具,它允许您使用变量占位符定义模板 HTML,编译它们,然后插入变量值。例如,您可以在 HTML 中定义:

<script type="text/x-handlebars-template" id="table-data-template">
    <table class="table">
        <thead>
            <tr>
                <th> Previous Searches: </th>
            </tr>
        </thead>

        <tr>
            {{data}}
        </tr>
    </table>
</script>

在你的 JS 中,你会做类似的事情:

$('#submit').click(function(e){ 
    e.preventDefault();
    var renderData = Handlebars.compile($("#table-data-template").html());
    var search=$('#search').val();
    $('#output').html(renderData({data: search});
}

超级干净。但是您必须花一些时间阅读 Handlebars 和所有相关内容。

如果你没有在你的应用程序中做很多这种基于模板的工作,因此 Handlebars 可能有点矫枉过正,你可以简单地在你的 JS 中定义 HTML 模板,如下所示:

$('#submit').click(function(e){ 
    e.preventDefault();
var search=$('#search').val();
$('#output').html(
    "<table class='table'>
        <thead>
            <tr>
                <th> Previous Searches: </th>
            </tr>
        </thead>

        <tr>" + search +     
        "</tr>
    </table>");

所以从字面上写出 HTML 的字符串,它将被注入到你的输出中,并在那里连接你的搜索结果。不是超级干净,但如果你只这样做一次,就完成了工作。