【问题标题】:Save data comming from xhr response to file js将来自 xhr 响应的数据保存到文件 js
【发布时间】:2021-11-15 21:12:58
【问题描述】:

我有一个产生文本数据的端点,并且知道如果用户单击开始/停止,我想将这些数据保存在前端文件中

我目前的方法如下所示,但它不起作用

var el = document.getElementsByClassName(".fa-file-download");

function saving(){
    let xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://127.0.0.0:8000/data');
    xhr.responseType = 'text';
    xhr.send();
    xhr.onload = function(e) {
      if (this.status == 200) {
          
          var blob = new Blob([this.response], {type: 'text'});
        
          let a = document.getElementsByClassName(".fa-save");
          a.style = "display: none";
          let b = document.getElementsByClassName(".fa-file-download");
          b.style = "display: block"
          
          let url = window.URL.createObjectURL(blob);
          b.href = url;
          
          b.download = 'logFile.txt';
          if (el.addEventListener) {
            el.addEventListener("click", function() {
                b.click();
            });
         
          
          window.URL.revokeObjectURL(url);
      }
  };
};

};

html部分

 <i class="far fa-save" ></i>
 <i class="fas fa-file-download" onclick="saving()"></i>

【问题讨论】:

    标签: javascript jquery xmlhttprequest


    【解决方案1】:

    您的代码中有几个问题

    • 您在.fa-file-download 中分配了href,这不是&lt;a&gt; 元素
    • 您已经有一个用于saving 函数的内联 onclick,但您在底部的代码中再次绑定了 onclick
    • 在您的 javascript 中,您有 2 个变量选择相同的元素 elb

    试试下面这段代码,看看它现在是否可以工作

        function saving(){
        let xhr = new XMLHttpRequest();
        xhr.open('GET', 'https://127.0.0.0:8000/data');
        xhr.responseType = 'text';
        xhr.send();
        xhr.onload = function(e) {
          if (this.status == 200) {
              
              var blob = new Blob([this.response], {type: 'text'}),
                  newA = document.createElement("a"); // new line
            
              let a = document.getElementsByClassName(".fa-save");
              a.style = "display: none";
              let b = document.getElementsByClassName(".fa-file-download");
              b.style = "display: block";
              
              let url = window.URL.createObjectURL(blob);
              b.href = url;
              // new line
              newA.href = url;
              newA.download = "logFile.txt";
              newA.click()
              newA.remove()
    
              // b.download = 'logFile.txt';
              // if (el.addEventListener) {
              //   el.addEventListener("click", function() {
              //       b.click();
              //   });
             
              
              window.URL.revokeObjectURL(url);
          }
          };
        };
    

    【讨论】:

      猜你喜欢
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-26
      • 1970-01-01
      • 2011-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多