基于jq和纯js的 读取本地.txt文件的方法

源网址

好像ajax本来就可以读到.txt

  1. <!DOCTYPE HTML>
  2. <html>
  3.  
  4. <head>
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  6. <title>读取txt文件</title>
  7. </head>
  8.  
  9. <body>
  10. <script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.js"></script>
  11. <script>
  12. $.ajax({
  13. url: "txt.txt",
  14. success: function(data, status) {
  15. console.log(arguments)
  16. console.log(data)
  17. },
  18. error: function(data, status) {
  19. console.log(arguments)
  20. }
  21. });
  22.  
  23. /**/
  24.  
  25. function readTxt() {
  26. var xhr = new XMLHttpRequest();
  27. xhr.open("get", "txt.txt", true);
  28. xhr.send();
  29. xhr.onreadystatechange = function() {
  30. if(xhr.readyState == 4 && xhr.status == 200) {
  31. console.log(xhr);
  32. console.log(xhr.responseText);
  33. } else if(xhr.status == 404) {
  34. console.log(xhr.status);
  35. }
  36. };
  37. }
  38. readTxt()
  39. </script>
  40. </body>
  41.  
  42. </html>
原文地址:https://www.cnblogs.com/jscs/p/13441475.html