问题: url中有带加号+的内容时会变成空格
解决: 将加号+替换成%2B即可
示例: encodeURI(str).replace(/\+/g,'%2B')
转码测试:var str="来了coming. ,/?:@&=+$#|-_.!~*'()。";
转码一:encodeURI(str);
结果:"%E6%9D%A5%E4%BA%86coming.%20,/?:@&=+$#%7C-_.!~*'()"
说明:encodeURI无法转码. ,/?:@&=+$#|-_.!~*'()
转码二:encodeURIComponent(str);
结果:"%E6%9D%A5%E4%BA%86coming.%20%2C%2F%3F%3A%40%26%3D%2B%24%23%7C-_.!~*'()"
说明:encodeURIComponent无法转码-_.!~*'()
总结:可使用正则解决一下str=str.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&");
再用上述编码,编码时注意应该使用下面这样的:
str=encodeURIComponent(encodeURIComponent(str));
即进行两次编码,因为后台收到值时自动解码一次。
如果后台是PHP则解码为:
$thisvalue = trim($_REQUEST['thisvalue']);
$thisvalue = urldecode($thisvalue);
前台解码则使用decodeURIComponent
解码,与PHP后台传值urlencode
相互对应。