简体   繁体   English

通过 Javascript 打开文本文件

[英]Opening a text file through Javascript

I have a text file called and I want to import the contents of this file and then output it to a paragraph in HTML.我有一个名为的文本文件,我想导入该文件的内容,然后将其输出到 HTML 中的一个段落。 How would I go about doing this?我该怎么做呢?

Use the XMLHttpRequest , like:使用XMLHttpRequest ,例如:

function World(){
  const xhr = new XMLHttpRequest;
  xhr.open('POST', 'hello_world.txt'); // change url accordingly
  xhr.onload = resp=>{
    document.getElementById('test').textContent = resp.responseText;
  }
  xhr.send();
}

Personally, I would get into the practice of separating HTML from JavaScript.就个人而言,我会尝试将 HTML 与 JavaScript 分离。 So, if we got rid of onload='World() in your <body> tag and you use external JavaScript like your test.js page, it would be like:所以,如果我们在你的<body>标签中去掉onload='World()并且你使用像test.js页面这样的外部 JavaScript,它会是这样的:

let doc, bod, I; // for use on other loads
addEventListener('load', ()=>{ // same as your body load Event - everything deeper than load is indented
doc = docmuent; bod = doc.body; I = id=>doc.getElementById(id);
const xhr = new XMLHttpRequest;
xhr.open('POST', 'hello_world.txt'); // change url accordingly
xhr.onload = resp=>{
  I('test').textContent = resp.responseText;
}
xhr.send();
}); // end load

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM