首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

AJAX 逐行讀取文字檔並動態生成 HTML 連結

     編輯:更多程式設計知識

需求場景

從伺服器讀取純文字檔 (.txt),每行一個 URL,前端需逐行解析並包裝成 <a><img></a> 結構輸出到頁面,且圖片檔名按行號遞增 (1.jpg, 2.jpg...)。

核心解決方案

使用 XMLHttpRequest (AJAX) 同步/非同步讀取檔案內容,利用 JavaScript 字串處理與正則表達式進行行分割與模板替換。

完整可執行代碼 (現代化重寫版)

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>AJAX 讀取 TXT 動態生成連結</title>
  <style>
    #myDiv a { display: inline-block; margin: 5px; border: 1px solid #ddd; padding: 5px; }
    #myDiv img { width: 100px; height: auto; vertical-align: middle; }
  </style>
</head>
<body>
  <div id="myDiv"><h2>點擊按鈕載入資料</h2></div>
  <button id="btnLoad">載入並轉換</button>

  <script>
    document.getElementById('btnLoad').addEventListener('click', loadTxtAndRender);

    function loadTxtAndRender() {
      const xhr = new XMLHttpRequest();
      // 使用相對路徑,請確保伺服器允許存取此檔案 (CORS 或同源)
      xhr.open('GET', '/ajax/test1.txt', true); // true = 非同步
      
      xhr.onload = function() {
        if (xhr.status === 200) {
          renderLinks(xhr.responseText);
        } else {
          console.error('請求失敗:', xhr.status);
          document.getElementById('myDiv').innerHTML = '<p style="color:red">載入失敗</p>';
        }
      };
      
      xhr.onerror = function() {
        console.error('網路錯誤');
      };
      
      xhr.send();
    }

    function renderLinks(text) {
      // 1. 分割行 (支援 \n, \r\n, \r),過濾空白行
      const lines = text.split(/\r?\n/).filter(line => line.trim() !== '');
      
      // 2. 映射為 HTML 字串陣列
      const htmlParts = lines.map((url, index) => {
        const safeUrl = url.trim(); // 去除首尾空白
        const imgNum = index + 1;
        // 使用模板字面字串構建 HTML,注意實際專務必做 XSS 防護 (此處假設來源可信)
        return `<a href="${escapeHtml(safeUrl)}" target="_blank" rel="noopener"><img src="${imgNum}.jpg" alt="圖片 ${imgNum}" /></a>`;
      });
      
      // 3. 一次性寫入 DOM (效能優於迴圈 innerHTML)
      document.getElementById('myDiv').innerHTML = htmlParts.join('\n');
    }

    // 簡易 HTML 轉義防 XSS
    function escapeHtml(str) {
      return str.replace(/[&<>"]/g, 
        tag => ({'&': '&', '<': '<', '>': '>', '"': '"'}[tag]));
    }
  </script>
</body>
</html>

關鍵技術點解析

1. 同步 vs 非同步

  • 原始碼使用 false (同步),會阻塞瀏覽器 UI,**強烈不建議**。
  • 現代寫法必須使用 true (非同步) + onload 回呼或 fetch API + async/await。

2. 字串分割與正則

  • text.split(/\r?\n/) 同時支援 Windows (\r\n)、Linux/Mac (\n) 換行符。
  • .filter(line => line.trim() !== '') 移除空白行。

3. 動態生成與索引

  • 使用 Array.map() 獲得索引 index,對應圖片編號 index + 1。
  • 陣列 join() 後一次性賦值 innerHTML,減少重排重繪。

4. 安全性:XSS 防護

若文字檔來源不可信 (如使用者上傳),**務必**對 URL 與輸出 HTML 進行轉義。範例中包含簡易 escapeHtml 函式,實際專案建議使用成熟庫 (如 DOMPurify)。

進階擴充:使用 Fetch API (現代標準)

async function loadTxtAndRenderModern() {
  try {
    const response = await fetch('/ajax/test1.txt');
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    const text = await response.text();
    renderLinks(text);
  } catch (err) {
    console.error(err);
    document.getElementById('myDiv').innerHTML = '<p style="color:red">載入異常</p>';
  }
}

結語

從傳統 XMLHttpRequest 到現代 Fetch API,核心邏輯皆為「請求文本 → 分割行 → 映射模板 → 渲染 DOM」。掌握此模式,可輕鬆應對 CSV、JSONL 等逐行資料格式的前端處理需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved