![](/img/trans.png)
[英]get html file from href and load it into the page using vanilla javascript
[英]txt file wont load by using vanilla javascript
我正在尝试使用简单的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文件。
注意,我在vscode上使用实时服务器
xhr.send()应该在xhr.onload()之外
xhr.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.