You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在HTML中通过GET请求加载并展示多个随机命名XML文件?

Alright, let's figure out why your wildcard *.xml approach isn't working and walk through practical solutions to load multiple (and dynamically generated) XML files into your HTML table.

Why *.xml Doesn't Work

Browsers' XMLHttpRequest (or modern fetch API) don’t support wildcard paths natively. When you send a request to *.xml, the server treats that as a literal filename—there’s no built-in logic to return all matching XML files. On top of that, front-end JavaScript can’t directly browse server directories due to security restrictions (same-origin policy and filesystem access limits).

The most reliable fix is to add a simple backend endpoint that returns a list of all XML files in your target folder. Your front-end can then fetch this list, loop through each filename, and load the XML files one by one.

Example Backend (Node.js/Express)

If you’re using Node.js, here’s a quick endpoint to generate the file list:

const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();

// Endpoint to get all XML files in the target folder
app.get('/get-xml-files', (req, res) => {
  const xmlFolderPath = path.join(__dirname, 'path/to/your/xml/folder'); // Replace with your actual folder path
  fs.readdir(xmlFolderPath, (err, files) => {
    if (err) return res.status(500).send('Failed to read XML directory');
    // Filter only files ending with .xml
    const xmlFiles = files.filter(file => file.endsWith('.xml'));
    res.json(xmlFiles);
  });
});

app.listen(3000, () => console.log('Server running on http://localhost:3000'));

Front-End Code to Load Multiple XML Files

Modify your existing code to first fetch the file list, then load each XML file:

// Fetch list of XML files from the backend
async function getXmlFileList() {
  try {
    const response = await fetch('/get-xml-files'); // Match your backend endpoint URL
    return await response.json();
  } catch (error) {
    console.error('Error fetching XML file list:', error);
    return [];
  }
}

// Load all XML files and render them using your existing table logic
async function loadAllXmlDocs() {
  const xmlFiles = await getXmlFileList();
  
  xmlFiles.forEach(fileName => {
    const xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
      if (this.readyState === 4 && this.status === 200) {
        myFunction(this); // Reuse your existing XML-to-table rendering function
      }
    };
    xmlhttp.open('GET', fileName, true);
    xmlhttp.send();
  });
}

// Your existing XML parsing/rendering function (keep your logic here)
function myFunction(xml) {
  // Your existing code to parse XML and build the HTML table...
}

// Load all files when the page loads
window.addEventListener('load', loadAllXmlDocs);
Solution 2: Monitor for Newly Generated XML Files

Since your folder keeps generating random-named XML files, add a polling mechanism to check for new files periodically (without reloading existing ones):

let loadedFileNames = []; // Track already loaded files to avoid duplicates

async function checkForNewXmlFiles() {
  const currentFiles = await getXmlFileList();
  // Filter out files we've already loaded
  const newFiles = currentFiles.filter(file => !loadedFileNames.includes(file));
  
  if (newFiles.length > 0) {
    // Load and render new files
    newFiles.forEach(fileName => {
      const xmlhttp = new XMLHttpRequest();
      xmlhttp.onreadystatechange = function() {
        if (this.readyState === 4 && this.status === 200) {
          myFunction(this);
        }
      };
      xmlhttp.open('GET', fileName, true);
      xmlhttp.send();
    });
    // Update our tracked files
    loadedFileNames = [...loadedFileNames, ...newFiles];
  }
}

// Check for new files every 5 seconds (adjust the interval as needed)
setInterval(checkForNewXmlFiles, 5000);
Note for Local Testing (file:// Protocol)

If you’re testing locally without a server, browsers restrict filesystem access for security. To work around this:

  • Use a simple local dev server (like the http-server npm package: run npx http-server in your project folder).
  • For Chrome, launch it with the --allow-file-access-from-files flag (only for testing, not recommended for production).

内容的提问来源于stack exchange,提问作者Jerry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 11:32:42