Call HttpHandler from javascript

坚强是说给别人听的谎言 提交于 2019-12-11 03:05:27

问题


I have a simple page with button which calls HttpHandler via JavaScript.

HttpHandler gets lots of files and adds them to a zip file, after finishing work zip file will be added to Response.

This operation can take several minutes. I would like to execute some JavaScript function after finishing work of HttpHandler.

How can I do it?

My code:

<asp:Button ID="btnDownload" runat=server Text="Download" OnClientClick="Download()" />

<script type="text/javascript">
    function Download()
    {
        var url = 'FileStorage.ashx';
        window.open(url);            
    }
</script>

UPD 1:

I have found other solution. Using XMLHttpRequest.

Code:

 <script type="text/javascript">
        var xmlHttpReq = createXMLHttpRequest();

        function Download() {
            var url = 'FileStorage.ashx';            
        xmlHttpReq.open("GET", url, false);
        xmlHttpReq.onreadystatechange = onResponse;
        xmlHttpReq.send(null);         
    }

    function onResponse() {
        if (xmlHttpReq.readyState != 4)
        { return; }        
        var serverResponse = xmlHttpReq.responseText;
        alert(serverResponse);        
     }

    function createXMLHttpRequest() {
        try { return new XMLHttpRequest(); } catch (e) { }
        try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { }
        try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { }
        alert("XMLHttpRequest not supported");
        return null;
    }
    </script>

In onResponse() I can see my zip file in responseText (binary). But I don't have any idea how I can say to browser to download result of working httphandler such as file.

Any ideas?


回答1:


I would use JQuery AJAX and then on success, write a function that will do whatever work you need it to. Plus with AJAX you can show the user an icon that says loading so they know something is actually processing, instead of the page just hanging and nothing appearing to happen.

$.ajax({
  url: "FileStorage.ashx",
  context: document.body,
  success: function(){
     // Whatever you want to do here in javascript.
  }
});


来源:https://stackoverflow.com/questions/6008362/call-httphandler-from-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!