简体   繁体   English

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

[英]txt file wont load by using vanilla javascript

I am trying to implement an ajax with simple txt file but the file won't load any suggestion 我正在尝试使用简单的txt文件实现ajax,但该文件不会加载任何建议

the html: 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> 

and the javascript file: 和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();
}
}

and this is the sample.txt file 这是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

Note, I'm trying to achieve it using vanilla javascript without any frameworks or library 请注意,我正在尝试使用不带任何框架或库的原始javascript实现它

As an output I get nothing once I click the button and even in the network tab in the inspector the txt file never even load. 作为输出,单击按钮后我什么也没得到,甚至在检查器的“网络”选项卡中也从未加载过txt文件。

在此处输入图片说明

Note, I'm using live sever on vscode 注意,我在vscode上使用实时服务器

xhr.send() should be outside xhr.onload() xhr.send()应该在xhr.onload()之外

xhr.onload() is the callback function to be executed when the request completes successfully. xhr.onload()是请求成功完成时要执行的回调函数。

refer the docs here https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestEventTarget/onload 请参阅此处的文档https://developer.mozilla.org/zh-CN/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> 

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

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