TXT-файл не загружается с использованием ванильного JavaScript - PullRequest
0 голосов
/ 21 февраля 2019

Я пытаюсь реализовать ajax с простым txt-файлом, но файл не загружает никаких предложений

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 голосов
/ 21 февраля 2019

xhr.send () должно быть за пределами xhr.onload ()

xhr.onload () - это функция обратного вызова, которая должна быть выполнена после успешного завершения запроса.

см. Здесь документыhttps://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestEventTarget/onload

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();
}
<!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> 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...