asp.net结合ajaxfileupload控件上传文件一直提示undefined问题

 今天做了用ajaxfileupload.js上次文件
遇到一个问题,弄好半天才解决掉
js代码:

function upload(title, RQ, DJ, DWinfo) { $.ajaxFileUpload( { url: 'AshxAllEvent/ReleaseKW.ashx?TI=' + title + "&TM=" + RQ + "&MJ=" + DJ + "&DW=" + DWinfo, secureuri: false, fileElementId: 'fup', //上传控件ID dataType: 'json', success: function(data, status) { if (status == "success") { alert(data.msg); } else { alert(data.msg+"Error"); } }, error: function(data, status, e) { alert(e); //就是在这弹出“语法错误” } }); }

ASHX处理代码:

HttpFileCollection postedFile = context.Request.Files; if (postedFile != null && postedFile.Count > 0) { string TI = context.Request.QueryString["TI"] == null ? "" : context.Request.QueryString["TI"].ToString(); string TM = context.Request.QueryString["TM"] == null ? "" : context.Request.QueryString["TM"].ToString(); string MJ = context.Request.QueryString["MJ"] == null ? "" : context.Request.QueryString["MJ"].ToString(); string DW = context.Request.QueryString["DW"] == null ? "" : context.Request.QueryString["DW"].ToString(); string ZW = ""; try { string savepath = ""; string tempPath = ""; tempPath = System.Web.HttpContext.Current.Server.MapPath("..//Temp//"); savepath = tempPath; string filename = Path.GetFileName(postedFile[0].FileName); ZW = filename; ZW = "{" + ZW + "}"; string sExtension = filename.Substring(filename.LastIndexOf('.')); if (!Directory.Exists(savepath)) Directory.CreateDirectory(savepath); string sNewFileName = filename.Substring(0, filename.IndexOf(".")); postedFile[0].SaveAs(savepath + @"/" + sNewFileName + sExtension); InsertKwInfoToDataBase( TI, ZW, TM, MJ, DW,ref error); if (error.Equals("")) { string res = "{/"status/" : /"success/",/"msg/": /"发布刊物成功!/"}"; context.Response.Write(res); } else { context.Response.Write("{/"status/" :/"error/",/"msg/" : /"" + error + "/"}"); } } catch (Exception ex) { context.Response.Write("{/"status/" : /"error/",/"msg/": /"" + ex.Message + "/"}"); } }  

但是除了上面这些还不够,在执行后,js提示一直是 undefined 是什么原因呢?找了好久一直没找到方法解决!
后来找不到,就踏实的js单步执行看看,结果发现ajaxfileupload.js中,返回获取的json数据带有其他杂质的字符串
比如:
ashx返回的json:

{"status" : "success","msg": "发布刊物成功!"}

aspx返回的json:

{'msg': '发布刊物成功!'}



知道了这个就好办了 ,对它进行过滤一下,就可以了。打开ajaxfileupload.js:
找到 uploadHttpData: function(r, type)函数
修改为:

uploadHttpData: function(r, type) { var data = !type; data = type == "xml" || data ? r.responseXML : r.responseText; data = data.replace("

", ""); //新加的 data = data.replace("
", "");//新加的 // If the type is "script", eval it in global context if (type == "script") jQuery.globalEval(data); // Get the JavaScript object, if JSON is used. if (type == "json") { //我只针对json模式 进行了修改 var data2 = new Array(); //新加的 data2 = data.split("}");//新加的 eval("data = " + data2[0] + "}");//修改后的 } // evaluate scripts within html if (type == "html") jQuery("
").html(data).evalScripts(); //alert($('param', data).each(function(){alert($(this).attr('value'));})); return data; }

这样基本就OK了!

你可能感兴趣的:(asp.net)