JavaScript新手求助:如何用双AJAX请求生成两个独立表格
Hey there! Great job getting the single table working—extending this to two tables is all about making your code reusable and keeping each AJAX request tied to its own target table. Let's walk through the changes step by step:
Key Improvements to Make
- Modularize table rendering: Create a reusable function that can populate any table with your data, instead of having separate logic for each table.
- Separate AJAX calls: Build a second fetch function for your service data, mirroring your existing host data function but targeting the right endpoint and table.
- Targeted DOM updates: Make sure when you clear or update rows, you only affect the specific table you're working with (no more accidentally clearing both tables!).
Updated Code
Your HTML is already set up correctly with both host_table and service_table—no changes needed there. Here's the revised JavaScript:
$(function() { // Trigger both data fetches when the page loads fetchHostData(); fetchServiceData(); }); // Helper for basic auth (unchanged) function make_base_auth(user, password) { var tok = user + ':' + password; var hash = btoa(tok); return 'Basic ' + hash; } // --- Reusable Table Rendering Function --- // This handles clearing existing rows, adding new ones, and styling function renderTable(tableId, dataArray, createRowContent) { // Clear only the rows in the target table (keep headers!) $('#' + tableId + ' tr:has(td)').remove(); // Add new rows using the provided row creation logic $.each(dataArray, function(index, item) { const row = $('<tr>'); // Call the custom function to generate TDs for this item createRowContent(row, item); row.appendTo('#' + tableId); }); // Apply color styling to the availability column (adjust index if needed) $('#' + tableId + ' tr').each(function() { const $td = $(this).find('td:eq(1)'); const value = parseInt($td.text()); if (value < 100) { $td.css('background-color', 'red'); } }); } // --- Host Data Fetch & Render --- function fetchHostData() { const time = new Date(); const end = Math.floor(Date.now() / 1000); const start = Math.floor(time.setDate(time.getDate() - 1) / 1000); const availReportUrl = "http://xx.xx.xx.xx/nagios/cgi-bin/archivejson.cgi?query=availability&availabilityobjecttype=hostgroups&hostgroup=ALM&assumedinitialhoststate=up&assumedinitialservicestate=ok&starttime=" + start + "&endtime=" + end; $.ajax({ type: "GET", url: availReportUrl, beforeSend: function(xhr) { xhr.setRequestHeader('Authorization', make_base_auth("nagiosadmin", "nagiosadmin")); }, dataType: 'json', timeout: 0, success: function(series) { // Use our reusable render function for host table renderTable('host_table', series.data.hostgroup.hosts, function(row, host) { row.append( $('<td>').text(host.name), $('<td>').text(parseInt(((host.time_up - host.time_down)/host.time_up)*100)) ); }); } }); } // --- Service Data Fetch & Render --- function fetchServiceData() { // Adjust these parameters to match your service availability endpoint const time = new Date(); const end = Math.floor(Date.now() / 1000); const start = Math.floor(time.setDate(time.getDate() - 1) / 1000); // Replace this URL with your actual service data endpoint const serviceReportUrl = "http://xx.xx.xx.xx/nagios/cgi-bin/archivejson.cgi?query=availability&availabilityobjecttype=servicegroups&servicegroup=YOUR_SERVICE_GROUP&starttime=" + start + "&endtime=" + end; $.ajax({ type: "GET", url: serviceReportUrl, beforeSend: function(xhr) { xhr.setRequestHeader('Authorization', make_base_auth("nagiosadmin", "nagiosadmin")); }, dataType: 'json', timeout: 0, success: function(series) { // Use our reusable render function for service table // Adjust the data path and row content to match your service JSON structure renderTable('service_table', series.data.servicegroup.services, function(row, service) { row.append( $('<td>').text(service.name), // Replace with your service name field $('<td>').text(parseInt(((service.time_up - service.time_down)/service.time_up)*100)) // Adjust calculation if needed ); }); } }); }
What Changed?
- Reusable
renderTablefunction: This takes care of clearing old rows, adding new ones, and applying the red background for low availability. You pass in the table ID, your data array, and a function that defines how to build each row's content—this makes it flexible for both host and service data. - Separate fetch functions:
fetchHostDataandfetchServiceDatahandle their own AJAX calls, targeting the correct endpoints. Each uses therenderTablefunction to populate its respective table. - Targeted DOM operations: Instead of clearing all
<tr>elements with TDs, we now only clear rows in the specific table we're updating (using$('#' + tableId + ' tr:has(td)')).
Important Notes
- Make sure to update the
serviceReportUrlto match your actual service availability endpoint (adjust parameters likeservicegroupto your needs). - Double-check the JSON structure for your service data—if the path to your services array is different than
series.data.servicegroup.services, update that in thesuccesscallback offetchServiceData. - The row creation logic for services might need tweaks if your service JSON has different field names (e.g., maybe
service.display_nameinstead ofservice.name).
This setup keeps your code clean, reusable, and ensures each AJAX request populates the correct table without interfering with the other.
内容的提问来源于stack exchange,提问作者user2439278
相关产品推荐
相关产品推荐

