![](/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.