您好,欢迎访问一九零五行业门户网

用JavaScript实现PHP的urlencode与urldecode函数_javascript技巧

很多朋友说javascript的decodeuri函数也可以实现,但有bug所有呢,下面看下下面的函数,经过测试使用暂时没什么问题,我在之前的文章说过,这个和php的urldecode函数根本不是一回事。下面是我根据高人的代码改写的javascript版的urldecode函数,参考的链接在开头提到的文章中有,就不一一列举了。和之前的urlencode函数一样,只实现了utf-8版的。
1、urlencode
使用方法: urlencode(str);
function urlencode(clearstring) { var output = ''; var x = 0; clearstring = utf16to8(clearstring.tostring()); var regex = /(^[a-za-z0-9-_.]*)/; while (x 1 && match[1] != '') { output += match[1]; x += match[1].length; } else { if (clearstring[x] == ' ') output += '+'; else { var charcode = clearstring.charcodeat(x); var hexval = charcode.tostring(16); output += '%' + ( hexval.length > 12) & 0x0f)); out += string.fromcharcode(0x80 | ((c >> 6) & 0x3f)); out += string.fromcharcode(0x80 | ((c >> 0) & 0x3f)); } else { out += string.fromcharcode(0xc0 | ((c >> 6) & 0x1f)); out += string.fromcharcode(0x80 | ((c >> 0) & 0x3f)); } } return out; } return output;}
2、urldecode
使用方法:urldecode(url);
function urldecode(encodedstring){ var output = encodedstring; var binval, thisstring; var myregexp = /(%[^%]{2})/; function utf8to16(str) { var out, i, len, c; var char2, char3; out = ; len = str.length; i = 0; while(i > 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: out += str.charat(i-1); break; case 12: case 13: char2 = str.charcodeat(i++); out += string.fromcharcode(((c & 0x1f) << 6) | (char2 & 0x3f)); break; case 14: char2 = str.charcodeat(i++); char3 = str.charcodeat(i++); out += string.fromcharcode(((c & 0x0f) << 12) | ((char2 & 0x3f) << 6) | ((char3 & 0x3f) < 1 && match[1] != '') { binval = parseint(match[1].substr(1),16); thisstring = string.fromcharcode(binval); output = output.replace(match[1], thisstring); } //output = utf8to16(output); output = output.replace(/\\+/g, ); output = utf8to16(output); return output;}
当服务器端通过php的urlencode转码的就可以使用js的urldecode进行解析即可。
其它类似信息

推荐信息