admin管理员组

文章数量:1399217

I use an <a> element to download a file in HTML page. It takes some seconds, so I want to show a loading by listening to the http response.

Is there a way to show loading when clicked <a> element, and close loading when download pleted?

This is what I want:

<a href="https://..." download>download file</a>

I use an <a> element to download a file in HTML page. It takes some seconds, so I want to show a loading by listening to the http response.

Is there a way to show loading when clicked <a> element, and close loading when download pleted?

This is what I want:

<a href="https://..." download>download file</a>
Share Improve this question edited Jun 12, 2019 at 7:05 wasanga7 2421 gold badge3 silver badges18 bronze badges asked Jun 12, 2019 at 6:15 edereder 732 silver badges10 bronze badges 3
  • I think you can look at this – shrys Commented Jun 12, 2019 at 6:17
  • Possible duplicate of Progress Bar (Download) Using HTML 5 – Justinas Commented Jun 12, 2019 at 7:06
  • @Justinas But i can't download a file by XMLHTTPRequest.I checked some solutions on stackoverflow.like: download-file.js. So,do i need to send a XMLHttprequest first, then use createObjectURL to create a URL? – eder Commented Jun 12, 2019 at 7:54
Add a ment  | 

2 Answers 2

Reset to default 5

There are two ways :

  1. Use ajax for listening event or receive data from Back-end :
$(document).ready(function(){
  $("button").click(function(){
    $.ajax({url: "/getData", success: function(result){
      $("#div1").html(result);
    }});
  });
});
  1. In addition , you can use socket.io to listen event from Back-end .

At server send event :

socket.emit('sendData', 'Your Data');

At client listen event :

 socket.on('sendData', function(data) {
        console.log(data); // Your Data
      });

XMLHttpRequest provides the ability to listen to various events that can occur while the request is being processed. Beneath those also is progress It checks if the amount of data that has been retrieved has changed.

var oReq = new XMLHttpRequest();

oReq.addEventListener("progress", updateProgress);

oReq.open("GET", url);

// progress on transfers from the server to the client (downloads)
function updateProgress (oEvent) {
  if (oEvent.lengthComputable) {
       // DO your Stuff here
  } else {
    // Unable to pute progress information since the total size is unknown
  }
}

Note: You need to add the event listeners before calling open() on the request. Otherwise the progress events will not fire.

本文标签: javascriptHow to listen for the http request by A html elementStack Overflow