DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>前端js读取本地md或txt文件内容title>
head>
<body>
<script>
function readTextFile(fileName) {
var rawFile = new XMLHttpRequest()
var filePath = location.origin + '/' + fileName
rawFile.open('GET', fileName, false)
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText
document.getElementById('showmd').innerHTML = allText
console.log(666.20001, allText, location)
}
}
}
rawFile.send(null)
}
script>
<div id="showmd">div>
<button onclick="readTextFile('text.md')">测试按钮button>
<button onclick="readTextFile('public/text.md')">测试按钮2button>
body>
html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31