简体   繁体   English

使用窗口对象下载CSV文件

[英]download a CSV file using window object

I am trying to create a link that will download a CSV file. 我正在尝试创建一个链接,该链接将下载CSV文件。 My current solution is to listen for a click event on that link and then attach a hidden form, and submit that form. 我当前的解决方案是监听该链接上的click事件,然后附加一个隐藏的表单,然后提交该表单。 I would like to set the window object equal to the link to the handler that creates the CSV. 我想将window对象设置为等于创建CSV的处理程序的链接。 However it doesn't seem to work, here is what I have so far. 但是,这似乎不起作用,这是我到目前为止所拥有的。 I AM NOT INTERESTED IN USING ANY ADDITIONAL LIBRARIES. 我对使用任何其他图书馆都不感兴趣。

This is the handler code that is used to create a dummy CSV file: 这是用于创建虚拟CSV文件的处理程序代码:

else if(action == "exportalldata")
{
    context.Response.Clear();
    context.Response.ContentType = "application/csv";
    context.Response.AddHeader("Content-Disposition", "attachment;     filename=yourData.csv");
    context.Response.Write("\"ID\", \"Description\", \"DTA\"\n");
    context.Response.Write("\"\test1\",\"test2\",\"test3\"\n");   
    context.Response.End();    
}

Form method, when link is clicked that event triggers this(that works): 表单方法,当单击链接时,事件将触发此事件(有效):

$form = $(document.createElement('form'))
        .attr({
              action: 'svc/export.ashx/exportAllData',
              method: 'POST'
         })
         .css('display', 'none')
         .appendTo('body');
$form.submit();
$form.empty().remove();

I would like to do the following: 我要执行以下操作:

<a id = "exportData" href="javascript:window.location='svc/export.ashx/exportAllData'">Export Variable List</a>

When I do that all that happens is I get a blank Screen and no CSV file ever downloads. 当我这样做时,所有事情发生了,我得到了一个空白屏幕,并且从未下载过CSV文件。 It would be nice if the link would also not lead the user away from the page that contains the link as well. 如果该链接也不会使用户也离开包含该链接的页面,那就太好了。 I tried setting target = "_blank" however that did not work. 我尝试设置目标=“ _blank”,但是没有用。

I used a jQuery plugin to solve that exact problem: 我使用jQuery插件来解决该确切问题:

http://johnculviner.com/category/jquery-file-download/ http://johnculviner.com/category/jquery-file-download/

You use a simple link like you are already doing and attach a click event that triggers the download via the plugin. 您可以像执行操作一样使用简单的链接,并附加一个点击事件,该事件通过插件触发下载。

The clever mechanism is detailed here . 聪明的机制在这里详细介绍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM