jquery ajax+json(插件) 提交数据,让人捉摸不透的是:【部分中文显示问号】
各位网友:
目前碰到一个棘手的难题,使用json格式封装页面数据提交到action,没有用表单,而是直接使用js获取数据,组织成json格式字符串,通过jquery的ajax功能提交到action中(请不要说为什么不用表单)。需求很明了。
1。组织数据封装到js对象
function doActive(kind,group,state,model,speed,settemp,lock){ this.fkind=kind; this.fgroup=group; this.fstate=state; this.fmodel=model; this.fspeed=speed; this.fsettemp=settemp; this.flock=lock;} var states=$("#New_fstate").val(); var model=$("#New_fmodel").val(); var speed=$("#New_fspeed").val(); var settemp=$("#New_fsettemp").val(); var lock=$("#New_flock").val(); var myData=new doActive(kindsArray,groupsArray,states,model,speed,settemp,lock); alert($.toJSON(myData)); $.ajax({ type:"post", url:"groupControl.do?operate=doAdd", data:$.toJSON(myData), dataType:"text", contentType:"application/json;charset=UTF-8", error:function(XmlHttpRequest, textStatus, errorThrown){ alert("操作异常" + XmlHttpRequest.responseText); }, success:function(data){ if(data==1){ showMsg("操作完成",4000,"success"); }else{ showMsg("操作异常",4000,"error"); } } });{"fkind":["张三","李四"],"fgroup":"["王五","赵七"]","fstate":""}BufferedReader br = new BufferedReader(new InputStreamReader( (ServletInputStream) request.getInputStream())); String line = null; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line); } String d=sb.toString(); //d=new String(d.getBytes("GB2312"),"UTF-8"); JSONObject jsonObj = JSONObject.fromObject(d);
alert("操作异常" + XmlHttpRequest.responseText);
},
success:function(data){
if(data==1){
//showMsg("操作完成",4000,"success");
alert(1);
}else{
//showMsg("操作异常",4000,"error");
alert(2);
}
}
});
}
=====================================
BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream()));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
String d=sb.toString();
d = URLDecoder.decode(d,"UTF-8");
System.out.println(d);
[解决办法]
页面中用js提供的内置编码函数encdoeURL()对提交的中文进行编码,servlet中再用4楼的方法
d = URLDecoder.decode(d,"UTF-8");
解码即可得到正确的中文
[解决办法]