JavaScript原生Ajax请求纯文本数据

源代码 ajax1.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ajax请求纯文本文档</title>
</head>
<body>
    <button type="button" id="button">请求纯文本</button>
</body>
</html>
<script type="text/javascript">
    //获取元素并添加事件
    document.getElementById('button').addEventListener('click',loadText);
    //创建loadText函数
    function loadText(){

       //创建XMLHttpRequst对象
        var xhr = new XMLHttpRequest();

       // console.log(xhr); //输出所创建里包含的东西
       //
       // 打开文件
       // open(请求方式type,访问文件url/file,是否异步async)
       xhr.open('get', 'a.txt', true);

       //两种请求方式:onload/onreadystatechange
       //onload 方式:
       xhr.onload = function(){
       //输出一下请求返回的文本
       console.log(this.responseText);
       }
       //
       //onreadystatechange  方式
       /*xhr.onreadystatechange = function(){
          console.log(this.responseText)
       }*/

      //发送请求
       xhr.send();
    }
</script>

源代码 a.txt:

dfbaksfkakkassl
fmaksdfkasnf
asndfnasdfndsl
asdfknfksdnfss

效果图:

 

原文地址:https://www.cnblogs.com/davis16/p/8666887.html