在回撥函式內訪問檔案內容並在控制檯上顯示——jQuery


假設以下內容為我們的檔案,我們需要使用 jQuery 讀取此檔案。

檔案詳情檔名 -

示例

以下是程式碼 -

 即時演示

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
   <input type="file" id="readFileDemo" onchange="chooseFile()">
</body>
<script>
   function chooseFile() {
      dataFromMyFile = document.getElementById("readFileDemo").files[0];
      readDataFromFile = new FileReader();
      readDataFromFile.onload = () => {
         data = readDataFromFile.result;
         console.log("Your File Data is=");
         console.log(data);
      };
      readDataFromFile.readAsText(dataFromMyFile);
   }
</script> 
</html>

要執行以上程式,請儲存檔名“anyName.html(index.html)”。右鍵單擊該檔案,然後在 VSCode 編輯器中選擇“使用即時伺服器開啟”選項 -

輸出

這將在控制檯上產生以下輸出 -

現在,您可以單擊“選擇檔案”來從系統中選擇檔案。此處,我的檔名是 details。我們上傳了“details.txt”檔案 -

控制檯中的檔案內容 -

更新於: 09-11-2020

566 檢視次數

開啟你的 事業

透過完成本課程獲得認證

開始學習
廣告
© . All rights reserved.