txt文件将无法使用香草javascript加载

时间:2019-02-21 14:54:39

标签: javascript ajax

我正在尝试使用简单的txt文件实现ajax,但该文件不会加载任何建议

html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="app.js"></script>

<title>Ajax 1 - Text File</title>
</head>
<body>
<button id="button" onclick="loadText()">Get Text File</button>

</body>
</html> 

和javascript文件:

//Create event Listener of the Get Text File 


function loadText(){
// Create XHR object
var xhr = new XMLHttpRequest();
// OPEN - type, url/fileName, async
//console.log(xhr);
xhr.open('GET', 'sample.txt', true);

xhr.onload = function(){

    //HTTP statuses
    //200: OK
    //403: Forbiden
    //404: Not Found

    if(this.status == 200){
        console.log(this.responseText);
    }
    //Send Request
    xhr.send();
}
}

这是sample.txt文件

This massage form the text file just to ensure you have the ability to 
access the text file. so if you do good for you otherwise just keep 
trying

注意,我正在尝试使用不带任何框架或库的原始javascript来实现它

当我单击按钮时,作为输出我什么也没得到,即使在检查器的“网络”选项卡中,也永远不会加载txt文件。

enter image description here

注意,我在vscode上使用实时服务器

1 个答案:

答案 0 :(得分:1)

xhr.send()应该在xhr.onload()之外

xhr.onload()是请求成功完成时要执行的回调函数。

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestEventTarget/onload

处参考文档

XMLRecordSetWriter
and the javascript file:

//Create event Listener of the Get Text File 


function loadText(){
// Create XHR object
  var xhr = new XMLHttpRequest();
  // OPEN - type, url/fileName, async
  //console.log(xhr);
  xhr.open('GET', 'sample.txt', true);

  xhr.onload = function(){

      //HTTP statuses
      //200: OK
      //403: Forbiden
      //404: Not Found

      if(this.status == 200){
          console.log(this.responseText);
      }
      //Send Request
  }
  xhr.send();
}