Обновление таблицы HTML с AJAX не обрабатывается - PullRequest
0 голосов
/ 11 апреля 2019

Я новичок во всем этом AJAX, но я пытаюсь понять, как я могу обновить HTML-таблицу, используя AJAX.

Я использую флягу, которая первоначально заполняет таблицу HTML, затем я отправляю форму для выполнения запроса, и мне возвращаются новые данные.с этими новыми данными я хочу, чтобы AJAX обновил таблицу.В моем вызове Ajax уже есть график HighCharts, который работает правильно, я в основном фокусируюсь на части таблицы.

Если вы видите в AJAX, у меня есть переменная flatOrderedDictList, эта переменная - это то, на чем я фокусируюсьКак я могу отобразить таблицу с этими обновленными данными в AJAX?Я немного запутался в этом?

моя html-страница с таблицей, которую я хочу обновить ajax

<div style="padding-left: 20px; padding-right: 20px; padding-bottom: 50px;">

<table class="table table-hover">
  <thead>
    <tr>
      <th scope="col">User</th>
      <th scope="col">Customer</th>
      <th scope="col">Profile</th>
      <th scope="col">Role</th>
      <th scope="col">Image</th>
      <th scope="col">Packet Size</th>
      <th scope="col">Ingress Port Use</th>
      <th scope="col">Egress Port Use</th>
      <th scope="col">Date</th>
    </tr>
  </thead>
  <tbody>


   {% for item in flatOrderedDictList %}

    <tr>
        {% for key, value in flatOrderedDictList[loop.index0].items() %}
            <td>{{value}}</td>
        {%endfor%}
    </tr>

    {%endfor%}

    {% endif %}

  </tbody>
</table>

</div>

мой код ajax

$(document).ready(function() {


    $('form').on('submit', function(event) {


        $.ajax({
            data : {
               images: $('#images').val(),
               userID: $('#userID').val(),
               release: $('#release').val(),
               rsp_type: $('#rsp_type').val(),
               lc_type: $('#lc_type').val(),
               featuer_type: $('#featuer_type').val(),
               chassis_type: $('#chassis_type').val(),
               profile_name: $('#profile_name').val(),
               os_type: $('#os_type').val(),
               daterange: $('#daterange').val(),
               role: $('#role').val(),
               customer: $('#customer').val(),
               queryCount: $('#queryCount').val(),
               flatOrderedDictList: $('#flatOrderedDictList').val()

            },
            type : 'POST',
            url : '/performance_reports_query_result'
        })
        .done(function(data) {


            if (data.error) {
                $('#errorAlert').text(data.error).show();
                $('#successAlert').hide();
            }
            else {
                console.log('customer is ' + customer + 'flatOrderedDictList is ' + data.flatOrderedDictList + data.flatOrderedDictList.length);
                $('#successAlert').text('Successfully Found ' + data.queryCount + ' Results').show();
                $('#errorAlert').hide();

            }

            $(function () {
                Highcharts.setOptions({
                    lang: {
                        thousandsSep: ','
                    }
                });

            $('#container').highcharts({
                chart: {
                    type: 'column'
                },
                title: {
                    text: 'Performance Results Run'
                },
                legend: {
                    title: {
                        text: 'Applied Featuers <br/><span style="font-size: 9px; color: #666; font-weight: normal">(Click to hide)</span><br>--------<br>',
                        style: {
                            fontStyle: 'italic'
                        }
                    },
                },

                xAxis: [{
                        categories: data.image_list_query,
                        tickColor: 'black',
                        lineColor: 'black',
                        lineWidth: 1,
                        labels: {
                            style:{
                                color: 'black',
                            },
                        }
                    },

                    {

                    linkedTo: 0,
                    opposite: true,
                    categories: data.oid_list,
                    labels: {
                        style:{
                        color: 'red',
                        display: 'none' 
                            },
                        }
                    },

                    {

                    linkedTo: 0,
                    lineColor: 'white',
                    tickColor: 'black',
                    categories: data.customer_name_listAjax,
                    labels: {
                        style:{
                        color: 'black',
                        // display: 'none' 
                            },
                        }
                    }

                ],


                yAxis: {
                    min: 0,
                    title: {
                        text: 'Packets Per Second'
                    }
                },
                credits: {
                  enabled: false,
                  text: 'mastarke'
                },
                tooltip: {
                    headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
                    footerFormat: '</table>',
                    shared: true,
                    useHTML: true
                },
                 plotOptions: {
                    series: {
                        cursor: 'pointer',
                        point: {
                            events: {
                                click: function() {
                                    var tableDate = this.category;
                                    var clickedOid = this.series.chart.options.xAxis[1].categories[this.index];
                                    var image = this.category;
                                    window.location.href = '/performance_reports_detail' + clickedOid;

                                }
                            }
                        }
                    }
                },


                series: [{

                    name: 'FRAME SIZE',
                    data: data.framesize_list
                },
                { 

                    name: 'Baseline PPS',
                    data: data.baseline_traffic_value_list
                },
                {
                    name: 'Performance With Features',
                    data: data.PerformanceWithFeatures_list
                },

                ]
            });

            });

        }); 

        event.preventDefault();

    });

}); 

с консоли JS это то, что возвращается. JS Console Pic 1 JS Console pic 2

1 Ответ

0 голосов
/ 11 апреля 2019

Я не понимаю, хотите ли вы принести или вставить данные, но я оставляю один способ, как рендерить html с помощью js vanilla.

Помните, что если вы хотите сделать эту динамику, она отличается, этот способ работает только тогда, когда вы вызываете свой API один раз.

ТОНИРОВАТЬ

async function insertData() {
    const route = 'your api route';
    const response = await fetch(`${route}`);
    const json = await response.json();
    const thead = document.querySelector('#myThead');

    for (const i in json) {
        /* I don't know the response of your api then this code is if you response it's only a object with de values
            example 
            json = {
                User,
                Customer,
                etc,
                etc,
            }
        */

        if (json.hasOwnProperty(i)) {
            const element = json[i];
            thead.innerHTML += 
            `
                <th scope="col">${element}</th>
            `;
        }
    }
}

ВЫХОД HTML

  <thead id="myThead">
<tr>
  <th scope="col">User</th>
  <th scope="col">Customer</th>
  <th scope="col">Profile</th>
  <th scope="col">Role</th>
  <th scope="col">Image</th>
  <th scope="col">Packet Size</th>
  <th scope="col">Ingress Port Use</th>
  <th scope="col">Egress Port Use</th>
  <th scope="col">Date</th>
</tr>
</thead>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...