我想使用jQuery Ajax web方法下载文件,但它不起作用.
这是我对web方法的jQuery ajax调用:
function GenerateExcel() {
var ResultTable = jQuery('<div/>').append(jQuery('<table/>').append($('.hdivBox').find('thead').clone()).append($('.bDiv').find('tbody').clone()));
var list = [$(ResultTable).html()];
var jsonText = JSON.stringify({ list: list });
$.ajax({
type: "POST",url: "GenerateMatrix.aspx/GenerateExcel",data: jsonText,contentType: "application/json; charset=utf-8",dataType: "json",success: function (response) {
},failure: function (response) {
alert(response.d);
}
});
}
这是Web方法定义:
[System.Web.Services.WebMethod()]
public static string GenerateExcel(List<string> list)
{
HttpContext.Current.Response.AppendHeader("content-disposition","attachment;filename=FileEName.xls");
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.Write(list[0]);
HttpContext.Current.Response.End();
return "";
}
如何完成它?请帮帮我.
还有一件事:我想在客户端PC上下载它,而不是将其保存在服务器上.
解决方法
好吧,我用iframe完成了它
这是修改后的ajax函数调用
function GenerateExcel() {
var ResultTable = jQuery('<div/>').append(jQuery('<table/>').append($('.hdivBox').find('thead').clone()).append($('.bDiv').find('tbody').clone()));
var list = [$(ResultTable).html()];
var jsonText = JSON.stringify({ list: list });
$.ajax({
type: "POST",success: function (response) {
if (isNaN(response.d) == false) {
$('#iframe').attr('src','GenerateMatrix.aspx?ExcelReportId=' + response.d);
$('#iframe').load();
}
else {
alert(response.d);
}
},failure: function (response) {
alert(response.d);
}
});
}
这是设计部分
<iframe id="iframe" style="display:none;"></iframe>
在页面加载我的代码看起来像这样
Response.AppendHeader("content-disposition","attachment;filename=FileEName.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.Write(tablehtml);
Response.End();