日期:2014-05-16  浏览次数:20354 次

解决JS提交url中存在中文的问题
在项目中经常回存在通过JS去请求操作的事件发生,而这些请求的url链接又通常会使用到中文,

而这些中文在JS中可以正常alert出来,但是提交给后台时就显示成乱码了。

这里提供一个解决方案,基本原理就是在JS中将中文转码成URI方式,如下:






        var queryTitle = document.getElementByIdx_x_x('queryTitle').value;  
        queryTitle=encodeURI(queryTitle);
        queryTitle=encodeURI(queryTitle);        //据说需要转2次



然后在后台获取的时候,解码URI:



        String newTitle = request.getParameter("newTitle");
        newTitle = java.net.URLDecoder.decode(newTitle, "utf-8");



这样就可以了



js:

function getDoctorMobile(currentElement,nextElement){
  var selected=currentElement.options[currentElement.selectedIndex].value;
  selected=encodeURI(selected);
        selected=encodeURI(selected);      
  if(selected != ''){
  jQuery.getJSON("${root}/admin/ajax/sys/area.do?action=GetDoctorMobile&doctorName="+selected,
     function(items){
       var output = [];
       jQuery.each(items, function(i,item){
         output.push('<option value="'+ item.mobile +'">'+ item.mobile +'</option>');
          });    
          $('#'+nextElement).html(output.join(''));
          $('#'+nextElement).css('display','');
     });
 
     }
}

java:

public String doGetDoctorMobile(Map<String, Object> context, CGI cgi) throws UnsupportedEncodingException {

  String name = cgi.getString("doctorName");
  name = java.net.URLDecoder.decode(name, "utf-8");

  Long hospitalId = (Long) cgi.getSession().getAttribute("hospitalId");
  if(hospitalId != null && StringUtils.isNotBlank(name)){

   UserInfo info = new UserInfo();
   info.setMedicalAgencyId(hospitalId);
   info.setDoctorName(name);
   Query<UserInfo> query = new Query<UserInfo>();
   query.setQueryObject(info);
   List<UserInfo> users  = userService.queryDoctor(query);
   writeJsonResponse(users, cgi);
  }
  return null;
}