从 javascript 调用 HttpHandler
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6008362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call HttpHandler from javascript
提问by Ukraine
I have a simple page with button which calls HttpHandler via JavaScript.
我有一个带有按钮的简单页面,它通过 JavaScript 调用 HttpHandler。
HttpHandler gets lots of files and adds them to a zip file, after finishing work zip file will be added to Response.
HttpHandler 获取大量文件并将它们添加到一个 zip 文件中,完成工作后将 zip 文件添加到 Response。
This operation can take several minutes. I would like to execute some JavaScript function after finishing work of HttpHandler.
此操作可能需要几分钟时间。我想在完成 HttpHandler 的工作后执行一些 JavaScript 函数。
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:
更新 1:
I have found other solution. Using XMLHttpRequest.
我找到了其他解决方案。使用 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.
在 onResponse() 中,我可以在 responseText(二进制)中看到我的 zip 文件。但我不知道如何告诉浏览器下载工作 httphandler 的结果,例如文件。
Any ideas?
有任何想法吗?
回答by Dietpixel
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.
我会使用 JQuery AJAX,然后在成功后,编写一个函数来完成您需要的任何工作。加上 AJAX,您可以向用户显示一个表示正在加载的图标,以便他们知道实际正在处理某些内容,而不是页面只是挂起而似乎什么也没有发生。
$.ajax({
url: "FileStorage.ashx",
context: document.body,
success: function(){
// Whatever you want to do here in javascript.
}
});