如何在没有JQuery的情况下在Javascript中获取文件的内容

How to get file's content in Javascript without JQuery

本文关键字:获取 文件 Javascript 情况下 JQuery      更新时间:2023-09-26

通常,为了完成网页中的某些任务,通常需要将存储在服务器中的文件中的内容加载到Javascript变量中或将其显示在HTML元素中。

如何在不依赖 JQuery 的情况下做到这一点?

我发现最简单的方法之一是创建一个函数来获取文件并在下载准备就绪时回调另一个函数。因此,在下面的示例中,当加载"test.txt"文件内容时,它显示在 pre 元素中。

<html>
<body>
<pre id="output"></pre>
</body>
<script type="text/javascript">
function get_file(url, callback)
{
    xmlhttp=new XMLHttpRequest();
    xmlhttp.open("GET", url, true);
    xmlhttp.onreadystatechange = function()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            callback(xmlhttp.responseText);
        }
    }
    xmlhttp.send();
}
get_file("test.txt", function(response)
{
    document.getElementById("output").innerHTML=response;
});
</script>
</html>

重要

如果你想使XMLHttpRequest同步,只需更改行

xmlhttp.open("GET", url, true);

xmlhttp.open("GET", url, false);

但它将以挂起您的网页为代价,直到加载数据。

尝试使用 fetch:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

它比XMLHttpRequest更容易使用。

然后,获取资源后,使用 insertAdjacentHtml 将其添加到文档正文:https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

fetch("test.json")
  .then(function(response) {
           return response.json();
        })
  .then(function(json) {
           document.body.insertAdjacentHtml("afterbegin", "<p>" + json + "</p>);
        });
  .catch(function(error) {
             console.log('There has been a problem with your fetch operation: ' + error.message);
          });