JSON更新时自动重载JS刷新表格,后续对接CURL API
Let's break down your requirements into actionable implementations that fit your existing Bootstrap/jQuery setup, with clean, maintainable code.
1. Auto-Reload Data When thinker.json Changes
To automatically refresh your table when the JSON file updates, we have two practical approaches—pick the one that fits your needs:
Option A: Efficient Conditional Polling
This method checks the file periodically but only fetches new data if it’s actually changed (using server headers like Last-Modified), cutting down on unnecessary network calls.
let lastModified = null; // Core function to refresh table content function refreshTable(data) { // Clear existing rows first to avoid duplicates $("#thinker_table tbody").empty(); let thinkerRows = ''; $.each(data.data, function(key, value) { // Assign status indicator class const statusClass = value.status.toLowerCase() === "online" ? "online" : "offline"; // Build full row with all your required columns thinkerRows += `<tr> <td>${value.name}</td> <td>${value.mac}</td> <td>${value.status}</td> <td><div class="${statusClass}"></div></td> <td> <button class="btn btn-sm btn-primary" onclick="openPopup('RoutineDetails.php')">Show Routines</button> </td> <td> <button class="btn btn-sm btn-secondary" onclick="openPopup('DeviceDetails.php')">Show Devices</button> </td> </tr>`; }); $("#thinker_table tbody").append(thinkerRows); } // Helper for consistent popup behavior function openPopup(url) { window.open(url, 'popUpWindow', 'height=500,width=700,left=100,top=100,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes'); } // Fetch data with change detection function loadThinkerData() { $.ajax({ url: "thinker.json", dataType: "json", headers: { "If-Modified-Since": lastModified || "" }, success: function(data, textStatus, xhr) { // Update timestamp for next check lastModified = xhr.getResponseHeader("Last-Modified"); refreshTable(data); }, statusCode: { 304: function() { console.log("No updates to thinker.json—skipping refresh"); } } }); } // Initialize on page load + set auto-refresh interval $(document).ready(function() { loadThinkerData(); setInterval(loadThinkerData, 30000); // Refresh every 30 seconds (adjust as needed) });
Option B: Simple Interval Polling
If you don’t need to optimize for unchanged files, a basic timer-based refresh works quickly:
// Use the same refreshTable and openPopup functions from Option A function loadThinkerData() { $.getJSON("thinker.json", function(data) { refreshTable(data); }); } $(document).ready(function() { loadThinkerData(); setInterval(loadThinkerData, 15000); // Refresh every 15 seconds });
2. Switch to CURL-Style API Requests
When moving from a local JSON file to a backend API, use jQuery’s $.ajax to match your API’s requirements (HTTP method, headers, request body). Here’s how to adjust:
Example: GET API Request (with Auth)
If your API uses GET and requires authentication:
// Replace the loadThinkerData function with this function loadThinkerData() { $.ajax({ url: "https://your-api-endpoint.com/thinkers", // Replace with your API URL method: "GET", dataType: "json", headers: { "Authorization": "Bearer YOUR_AUTH_TOKEN", // Add required auth headers "Content-Type": "application/json" }, success: function(data) { // Assume API returns data in { data: [...] } format (match your JSON structure) refreshTable(data); }, error: function(xhr, status, error) { console.error("Failed to fetch API data:", error); // Show user-friendly error message $("#thinker_table tbody").html("<tr><td colspan='6' class='text-center text-danger'>Failed to load data</td></tr>"); } }); }
Example: POST API Request (with Filters)
If your API requires a POST request to send filters or parameters:
function loadThinkerData() { $.ajax({ url: "https://your-api-endpoint.com/thinkers", method: "POST", dataType: "json", contentType: "application/json", headers: { "Authorization": "Bearer YOUR_AUTH_TOKEN" }, data: JSON.stringify({ // Add any request body parameters your API needs filter: "active", location: "office" }), success: function(data) { refreshTable(data); }, error: function(xhr, status, error) { console.error("API Error:", error); } }); }
Full Updated Code (Combined)
Here’s the complete integrated code with auto-refresh and API-ready structure:
<!-- CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" /> <!-- Status Indicator Styles --> <style> .online { height: 25px; width: 25px; background: green; border-radius: 50%; border: 1px solid; display: inline-block; } .offline { height: 25px; width: 25px; background: red; border-radius: 50%; border: 1px solid; display: inline-block; } </style> <!-- HTML Table --> <div class="col-md-8"> <table class="table table-bordered table-striped" id="thinker_table"> <thead class="thead-dark"> <tr> <th>Thinker Name</th> <th>MAC Address</th> <th>Status</th> <th>Indicator</th> <th>Show Routines</th> <th>Show Devices</th> </tr> </thead> <tbody> <!-- Content populated by JavaScript --> </tbody> <tfoot> <tr> <th>Thinker Name</th> <th>MAC Address</th> <th>Status</th> <th>Indicator</th> <th>Show Routines</th> <th>Show Devices</th> </tr> </tfoot> </table> </div> <!-- JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script> <script> let lastModified = null; function refreshTable(data) { $("#thinker_table tbody").empty(); let thinkerRows = ''; $.each(data.data, function(key, value) { const statusClass = value.status.toLowerCase() === "online" ? "online" : "offline"; thinkerRows += `<tr> <td>${value.name}</td> <td>${value.mac}</td> <td>${value.status}</td> <td><div class="${statusClass}"></div></td> <td> <button class="btn btn-sm btn-primary" onclick="openPopup('RoutineDetails.php')">Show Routines</button> </td> <td> <button class="btn btn-sm btn-secondary" onclick="openPopup('DeviceDetails.php')">Show Devices</button> </td> </tr>`; }); $("#thinker_table tbody").append(thinkerRows); } function openPopup(url) { window.open(url, 'popUpWindow', 'height=500,width=700,left=100,top=100,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes'); } // Option 1: Load from local JSON with conditional refresh function loadThinkerData() { $.ajax({ url: "thinker.json", dataType: "json", headers: { "If-Modified-Since": lastModified || "" }, success: function(data, textStatus, xhr) { lastModified = xhr.getResponseHeader("Last-Modified"); refreshTable(data); }, statusCode: { 304: () => console.log("No updates to thinker.json") } }); } // Option 2: Load from API (uncomment and replace above function) /* function loadThinkerData() { $.ajax({ url: "https://your-api-endpoint.com/thinkers", method: "GET", dataType: "json", headers: { "Authorization": "Bearer YOUR_AUTH_TOKEN" }, success: function(data) { refreshTable(data); }, error: (xhr, status, err) => { console.error("API Error:", err); $("#thinker_table tbody").html("<tr><td colspan='6' class='text-center text-danger'>Failed to load data</td></tr>"); } }); } */ // Initialize $(document).ready(function() { loadThinkerData(); setInterval(loadThinkerData, 30000); // Refresh every 30 seconds }); </script>
Quick Notes:
- I updated the row generation to include all your original columns (Indicator, Show Routines/Devices) since your initial code only rendered 3 columns.
- The
openPopuphelper reduces code duplication and keeps popup behavior consistent. - For API requests, adjust the URL, HTTP method, headers, and request body to match your backend’s specifications.
- Tweak the interval time (in milliseconds) based on how often you expect data changes.
内容的提问来源于stack exchange,提问作者arslaanmalik

