ajaxSubmit,json,struts2,提示保存“json返回值”
问题回顾:
1.需求:jsp页面通过<input type="file" ...>上传图片,后台对应action对图片做一些压缩,描边等处理后,将处理完的image返回到页面显示出来。
2.解决方案:采用ajaxSubmit提交,通过返回的json数据,将image填充到对应的<div>中
>>>>>>>>>>想看最终结果的直接下跳看标题5<<<<<<<<<<<<<<
遇到的几个问题:
假设<input type="file" id="upImage" name="upImage">
1.傻瓜式的认为,通过普通的ajax提交就能做到(代码如下)
$.ajax({ url:xxxx, data:'upImage='+ $('#upImage').val(), .... success:function(returnData){....}})
$.ajax({ url:xxxx, [color=red]data:$('#form1').formSerialize(),[/color] .... success:function(returnData){....}})
$("#form1").ajaxSubmit( {url : "previewImageDeal",datatype : "json", success : function(returnData){...}, error:function(){ alert('error'); }});
<action name="XXXX" method="XXXXXX"> <result name="deal" type="json"> <param name="includeProperties">dealStatus,dealMsg,dImgPath</param> </result></action>
String dealStatus = null; String dealMsg = null; String dImgPath = null; //图片处理 //给必要的变量赋值
private JSONObject returnData = null;//这个到底有没有用,还不知道,有点疲劳,不想做实验了response.setContentType("text/xml;charset=utf-8");//将返回结果保存到map中,然后转成jsonMap<String, String> map = new HashMap<String, String>();map.put();map.put();map.put();returnData = JSONObject.fromObject(map);//转JSONresponse.getWriter().print(returnData );//打印
<action name="xxxx"method="XXX" ><result name="deal" type="json"><param name="contentType">text/html</param><param name="includeProperties">returnData</param></result></action>5.3 js关键部分[color=red]说明:java中通过print打印了想要的json结果,struts.xml中又通过includeProperties强行收留了returnData,所以在js的success方法中会看到两个json结果块。为什么要includeProperties呢,因为不加includeProperties标签或者加空标签(<param name="includeProperties"></param>)会得到一大大大大堆不想要的结果,看着就烦,而且还消耗系统和网络资源[/color]$("#form1").ajaxSubmit( {url : "action名字",//datatype : "json",//彻底注释掉 success : function(returnData){returnData = returnData.substring(0,returnData.indexOf('}')+1);//只要print的json结果var isWindow = false;//window系统路径是"" 要进行转换 linux不需要转换if(returnData.indexOf('\\\\') >= 0){isWindow = true;//将路径中的""替换,不然parseJSON会出错returnData = returnData.replace(/\\\\/g,'_');}var jsonData = jQuery.parseJSON(returnData);if(jsonData.dealStatus == '0'){//错误处理alert(jsonData.dealMsg);$('#upImage').val('');$('#previewTR').css({"height":"0px"});$('#previewDiv').html('');}else{//成功处理图片var tempImagPath = jsonData.previewImagePath ;var finalImagePath = jsonData.finalImagePath ;if(isWindow){//window系统将"_"再转换成"/"tempImagPath = tempImagPath.replace(/_/g,'/');finalImagePath = finalImagePath.replace(/_/g,'\\');}$('#finalImagePath').val(finalImagePath);$('#previewTR').css({"height":jsonData.previewHeight+'px'});$('#previewDiv').html('<img src="'+tempImagPath+'" />' );}}});