2012-06-07 25 views
1

您好我需要生成服務器端的一些文件,並將它們與AJAX返回動態文件,jQuery和ASHX與POST參數

我創建服務器下一個代碼(ASHX)

public void ProcessRequest(HttpContext context) 
    { 
     string dataViewID = context.Request.Form["dataViewID"]; 

     MyService service = new MyService(); 
     var data = service.GetStores(int.Parse(dataViewID), "", null); 
     IMyExportService exportservice = new MyExportService(); 

     HttpContext.Current.Response.ContentType = "application/octet-stream"; 
     HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + "export.cvs"); 

     using (var ms = new MemoryStream()) 
     { 
      using (var sw = new StreamWriter(ms)) 
      { 
       exportservice.ExportTo("csv", sw, data);     
       ms.Position = 0;             
       HttpContext.Current.Response.Write(ms.ToArray()); 
      } 

     } 
    } 

返回客戶端在客戶端我創建下一個代碼: $(「#btnexport」)。click(function(){ var paramData = {「dataViewID」:1524129,「filter」:「」,extent:null}; // full map $ .ajax({url:'/marketVuePortal/'+'FileExport.ashx', type:'POST',
dataType:「json」, data:{dataViewID:1524129},
success:function(result){ //這裏應該是什麼? (xhr){ alert(「error」); }}
)}

); 

但我有2個問題,我不知道爲什麼,但我總是得到錯誤,但在調試所有代碼運作良好。第二個是我不知道如何說瀏覽器,他需要保存頁面無需重新加載。

回答

1

/* * -------------------------------------------------------------------- * jQuery-Plugin - $.download - allows for simple get/post requests for files * by Scott Jehl, [email protected] * http://www.filamentgroup.com * reference article: http://www.filamentgroup.com/lab/jquery_plugin_for_requesting_ajax_like_file_downloads/ * Copyright (c) 2008 Filament Group, Inc * Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) and GPL (filamentgroup.com/examples/gpl-license.txt) licenses. * -------------------------------------------------------------------- */ jQuery.download = function(url, data, method){ //url and data options required if(url && data){ //data can be string of parameters or array/object data = typeof data == 'string' ? data : jQuery.param(data); //split params into form inputs var inputs = ''; jQuery.each(data.split('&'), function(){ var pair = this.split('='); inputs+=''; }); //send request jQuery(''+inputs+'') .appendTo('body').submit().remove(); }; };

這是我找到的解決方案。