jQuery的交付使用AJAX调用的文件 [英] jQuery delivery of a file with AJAX call
问题描述
如果我有一个AJAX调用返回,也就是说,一个CSV,我怎么让浏览器提示下载用户?下面,ProductsExport将返回的CSV在成功的数据。我只是需要什么,我会代替//交付文件给用户符合...
$。阿贾克斯({
键入:POST,
网址:/搜索/ ProductsExport
数据:$('#客户ID)序列化()。
成功:功能(数据){
//交付文件给用户!
},
错误:函数(XHR,textstatus,errorThrown){
警报(错误);
}
})
在后端我的C#code看起来像这样:
VAR aFileContent = Encoding.ASCII.GetBytes(出口);
VAR aMemoryStream =新的MemoryStream(aFileContent);
返回文件(aMemoryStream,text / plain的,
的String.Format({0}的.csv,客户ID));
您不能据我所知。不能使用AJAX在这里作为一个文件下载。 是 - 它是一个支持的数据类型为每jQuery的,但不是一个文件。您需要链接到文件的非Ajax请求或者通过链接或一个jQuery get请求。
请参阅: 无法打开下载的文件保存对话框 和 在数据类型 http://api.jquery.com/jQuery.ajax/
If I have an AJAX call that returns, say, a CSV, how do I get the browser to prompt the user for a download? Below, the ProductsExport will return the CSV in the success data. I just need what I'd replace the // Deliver file to user line with...
$.ajax({
type: "POST",
url: "/Search/ProductsExport",
data: $('#CustomerId').serialize(),
success: function (data) {
// Deliver file to user!!
},
error: function (xhr, textstatus, errorThrown) {
alert('Error');
}
})
My C# code on the back end looks like so:
var aFileContent = Encoding.ASCII.GetBytes(export);
var aMemoryStream = new MemoryStream(aFileContent);
return File(aMemoryStream, "text/plain",
string.Format("{0}.csv", CustomerId));
You cannot as far as I'm aware. You can't use ajax here as a file download. YEs - its a support datatype as per jQuery but not for a file. You need to link to the file for a non ajax request either via a link or a jQuery get request.
See: Unable to open download save dialog and "datatype" on http://api.jquery.com/jQuery.ajax/
这篇关于jQuery的交付使用AJAX调用的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!