-->

JQuery, Ajax, Handlebars clear table then repopula

2020-07-19 07:23发布

问题:

Build a form that goes out and grabs data then populates a table using handlebars.js. Works great on the first go around then won't populate again if data is changed. Any ideas on how to get this to work?

$('a.button').on("click", function(e){
        e.preventDefault();

        var date = $('#datepicker').val();
        var func = "get_all_swo_by_date";
        //$('table.output').empty();

        $.ajax({
            url: "../includes/db_functions.inc.php",
            type: "post",
            data: ({ p : date, f : func }),
            dataType: "json",
            success: function(results) {
                var source = $("#entry-template").html();
                var template = Handlebars.compile(source);
                $('table.output').empty();
                if(results.length > 0)
                {
                    $.each(results, function(i, context){
                        $('table.output').append( template(context) );
                    });
                } else {
                    $('table.output').append("There is no data to return.");
                }

            }
        });
    });

When the "a" with a class of button is clicked it populates the table.. (as stated above). Ok now when you change datepicker to another date and click the "a" with a class of button it will not repopulate the table.

If someone has a legitimate idea of why it doesn't work please let me know. Please don't just make up stuff. I can do that plenty on my own.. :)

回答1:

Ok so here is the answer in case anyone is looking for it down the road.

What I wanted to do was clear out the table before I appended changed data, so when I set the:

$('table.output').empty();

before the append I thought that might work. However, I was being lazy and had not take my handlebars.js template out to another file, so all I was doing is clearing out my template so it could not be repopulated. In essence it didn't even exist..

So create an external file called yourtemplate.handlebars and add your code to it. In my case it was swooutput.handlebars:

<tr>
<td>{{id}}</td>
<td>{{item_no}}</td>
<td>{{swo}}</td>
<td>{{team_number}}</td>
<td>{{employee_payrate}}</td>
<td>{{customer_number}}</td>
<td>{{customer_name}}</td>
<td>{{customer_number}}</td>
<td>{{week_ending}}</td>
</tr>

then create a templates.js file in a js folder like so:

Handlebars.getTemplate = function(name) {
if (Handlebars.templates === undefined || Handlebars.templates[name] === undefined)    {
    $.ajax({
        url : name + '.handlebars',
        success : function(data) {
            if (Handlebars.templates === undefined) {
                Handlebars.templates = {};
            }
            Handlebars.templates[name] = Handlebars.compile(data);
        },
        async : false
    });
}
return Handlebars.templates[name];
};

I got that from somewhere, but can't remember where at the moment. If I do I'll post the link. Anyway, instead of having the template in the page you use that function to grab the template (makes it faster than compiling at run time). Or you can use precompiled templates, I just find this method easier.

So here is the final jquery ajax call with the modified code:

$('a.button').on("click", function(e){
            e.preventDefault();

            var date = $('#datepicker').val();
            var func = "get_all_swo_by_date";
            //$('table.output').empty();

            $.ajax({
                url: "../includes/db_functions.inc.php",
                type: "post",
                data: ({ p : date, f : func }),
                dataType: "json",
                success: function(results) {
                    $('table.output').empty();

                    var template = Handlebars.getTemplate('swooutput');

                    $.each(results, function(i, context){
                            $('table.output').append( template(context) );
                    });

                }
            });
        });

I hope this helps the next person that comes along.



回答2:

Just add the

<thead> 

and

<tbody> tags. So your table will look something like:

<table id="tblUsers">

    <tr>
        <th>
            ID
        </th>
        <th>
            Name
        </th>
        <th>
            Last name
        </th>
        <th class="header">
            Username
        </th>
        <th>

            &nbsp; &nbsp;</th>
        <th>
            &nbsp;&nbsp;</th>
    </tr>  
    </thead>
    <tbody>

    </tbody>      

And your jQuery:

function _onSuccess(data) {
    console.log(data.d);
    $('#tblUsers > tbody').empty(); //HERE'S WHERE YOU CLEAN THE TABLE'S BODY OR TBODY
    $.map(data.d, function (item) {
        var rows = "<tr>"
            + "<td style='border:2px solid black; cursor: default;'>" + item.id_user + "</td>"
            + "<td style='border:2px solid black; cursor: default;'>" + item.name + "</td>"
            + "<td style='border:2px solid black; cursor: default;'>" + item.last_name + "</td>"
            + "<td style='border:2px solid black; cursor: default;'>" + item.username + "</td>"
            + "<td style='border:2px solid black; cursor: pointer;'><input type='button' class='btEdit' id='e" + item.id_user + "' ></td>"
            + "<td style='border:2px solid black; cursor: pointer;'><input type='button' class='btDel' id='d" + item.id_user + "'></td>"
            + "</tr>";
        $('#tblUsers tbody').append(rows);
    })
}