您当前位置: 首页 >  WEB技术 >  javascript解决URL传值时乱码的方法
2013/11/4 12:48:06 分类:WEB技术

javascript解决URL传值时乱码的方法

 URL中出现空格,等字符会乱码,这个是见到的一个比较不错的处理方式。调用时,把要传递的参数通过这个js方法转化一下就可以转化为%xx组成的一系列字符   服务端正常获取   有兴趣的可以试一下 ,具体代码如下:

 

function encodeURL(str){
 var s0, i, s, u;
 s0 = "";                // encoded str
 for (i = 0; i < str.length; i++){   // scan the source
  s = str.charAt(i);
  u = str.charCodeAt(i);          // get unicode of the char
  if (s == " "){s0 += "+";}       // SP should be converted to "+"
  else {
   if ( u == 0x2a || u == 0x2d || u == 0x2e || u == 0x5f || ((u >= 0x30) && (u <= 0x39)) || ((u >= 0x41) && (u <= 0x5a)) || ((u >= 0x61) && (u <= 0x7a))){       // check for escape
s0 = s0 + s;            // don\'t escape
   }
   else {                  // escape
if ((u >= 0x0) && (u <= 0x7f)){     // single byte format
s = "0"+u.toString(16);
s0 += "%"+ s.substr(s.length-2);
}
else if (u > 0x1fffff){     // quaternary byte format (extended)
s0 += "%" + (oxf0 + ((u & 0x1c0000) >> 18)).toString(16);
s0 += "%" + (0x80 + ((u & 0x3f000) >> 12)).toString(16);
s0 += "%" + (0x80 + ((u & 0xfc0) >> 6)).toString(16);
s0 += "%" + (0x80 + (u & 0x3f)).toString(16);
}
 
else if (u > 0x7ff){        // triple byte format
s0 += "%" + (0xe0 + ((u & 0xf000) >> 12)).toString(16);
s0 += "%" + (0x80 + ((u & 0xfc0) >> 6)).toString(16);
s0 += "%" + (0x80 + (u & 0x3f)).toString(16);
}
else {                      // double byte format
s0 += "%" + (0xc0 + ((u & 0x7c0) >> 6)).toString(16);
s0 += "%" + (0x80 + (u & 0x3f)).toString(16);
}
   }
  }
 }
 return s0;
}

本文由胡金金个人网站整理发布,转载请注明地址:http://www.hujinjin.com/info/320.html

凡标明来源于胡金金个人网站的文章,皆为本站整理发布,若转载此文必须附原文链接,对部分平台更改其文内容当自己原创者,胡金金个人网站将保留其追究权利!
个人资讯推荐
友情链接