I am using C# and JavaScript. my goal is to send an ajax request that results in a CSV file being downloaded. The CSV will be generated on the server side in an ashx page. Currently the application is able to download a CSV but by using a form instead of an AJAX request, however the backend code is the same.
Here is the ajax request I have which fails:
$.ajax({
url: "myDir/x.ashx/exportAllData",
type: 'POST',
data: {
id:8
},
success: function(ajaxResult){
console.log(ajaxResult);
}
});
Here is the Form method that does work:
var $form = $(document.createElement('form'))
.attr({
action: 'myDir/x.ashx/exportAllData',
method: 'POST'
})
.css('display', 'none')
.appendTo('body');
$form.submit();
$form.empty().remove();
Here is the code in the handler(C#), which is the same for both the above cases:
else if(action == "exportalldata")
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("test1,test2,test3,test4,test5");
context.Response.Clear();
context.Response.ContentType = "application/csv";
context.Response.AddHeader("Content-Disposition", "attachment;filename=data.csv");
context.Response.Write(sb.ToString());
context.Response.End();
}
The short answer is you can't. Browsers cannot download files via ajax. It has to be done via form post.
You could modify your server-side code to output to a static file within your webroot and return a URL pointing to it. You could then set window.location.href
to the URL.
If you populate date yourself you can use this
jQuery Plugin for Requesting Ajax-like File Downloads
example from link:
$.download('/export.php','filename=mySpreadsheet&format=xls&content=' + spreadsheetData );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.