使用 Jquery 和 Ajax 在 ASP.Net 中保存文件 [英] Using Jquery and Ajax to save a file in ASP.Net

查看:37
本文介绍了使用 Jquery 和 Ajax 在 ASP.Net 中保存文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个按钮,它使用 jQuery 和 ajax 调用服务器端脚本来创建文本文件并返回以下响应:

I have a button that uses jQuery and ajax to call a server side script to create a text file and sends back the following response:

Response.ContentType = "csv";
Response.AddHeader("Content-disposition", "attachment; filename=" + fName);
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(btFile);
Response.End();

但是,保存对话框不会出现.如果我不使用 ajax 并使用相同的代码执行完整的回发,它就可以工作.有什么想法吗?

However, the save dialog does not appear. If I don't use ajax and perform a full postback with the same code, it works. Any ideas?

这里是 jQuery 代码:

Here is the jQuery code:

$(function() {
    $('#reportButton').click(function() {
        $.ajax({
            type: "POST",
            url: "GenerateReport.aspx",
            data: "id=0",
            success: function(){
            }
        });
    });
});

推荐答案

您可以通过使用 jQuery 动态创建表单和 iframe 来伪造它,而不是使用 AJAX(正如 Brian 提到的那样,这不起作用)到.这是我找到的一个例子——你应该阅读评论以获得一些改进(比如如果您的页面没有返回正确的标题,则使用动态创建的 iframe 来防止出现问题.

Rather than using AJAX (which will not work, as Brian mentions), you can fake it by using jQuery to dynamically create a form and an iframe to post it to. Here is an example I found -- you should read through the comments for some improvements (like the use of a dynamically created iframe to prevent problems if your page does not return the proper headers).

这篇关于使用 Jquery 和 Ajax 在 ASP.Net 中保存文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆