txt文件不会使用普通javascript加载
我试图用简单的txt文件实现ajax,但该文件不会加载任何建议 html:txt文件不会使用普通javascript加载,javascript,ajax,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="i
<!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>
这是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上使用live severxhr.send应该在xhr.onload之外 xhr.onload是请求成功完成时要执行的回调函数 请参阅此处的文档 以及javascript文件: //创建Get文本文件的事件侦听器 函数加载文本{ //创建XHR对象 var xhr=新的XMLHttpRequest; //打开类型,url/文件名,异步 //console.logxhr; 打开'GET','sample.txt',true; xhr.onload=函数{ //HTTP状态 //200:好的 //403:禁止 //404:找不到 ifthis.status==200{ console.logthis.responseText; } //发送请求 } xhr.send; } ajax1-文本文件 获取文本文件
尝试移动xhr.send;在onload方法之外。使用锚标记及其下载attribute@brk感谢Vladimir Bogomolov评论工作的帮助。但是它应该在onload函数中吗?为什么一旦我将它移出它works@AbdallahRizkonload是请求完成时触发的事件。读这里
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