当前位置: 首页 > Web前端 > HTML5

GET请求参数中特殊字符的处理

时间:2023-04-04 22:58:55 HTML5

如果restful接口涉及:请求路径:10.200.xxx.xxx/custom-interfaces/file/请求类型:GET请求参数:path,模拟请求值为:/test{}。发起的请求路径应该是:http://10.200.xxx.xxx/custom-interfaces/file/?path=/test{}实际浏览器向后台发起的请求是:响应是400,问题所在in:{},因为特殊符号报错。解决方法:1、在拼接请求URL之前,可以先通过encodeURIComponent对path参数的参数值进行处理。例如:varparams={token:xxx};for(iteminparams){params[item]=encodeURIComponent(params[item]);}2、或者用RegExp代替varreg=newRegExp(/\%/,"g");varreg1=newRegExp(/\&/,"g");varparams={token:xxx};对于(参数中的项目){参数[项目]=字符串(参数[项目])。repalce(reg,"%25").replace(reg1,"%25");}特殊字符分类用于分隔URI组件的标点符号:;/?:@&=+$,#其他ASCII标点符号是编码:-\_。!~\*'()encodeURI和encodeURIComponent的区别:encodeURIComponent:传递参数时需要使用encodeURIComponent,这样组合的url才不会被#等特殊字符截断。此外,encodeURIComponent将只处理用于分隔URI组件的标点符号。没有其他标点符号被编码。encodeURI:在进行url重定向时,可以将EncodeURI作为一个整体来使用。encodeURI():不对用于分隔URI组件的标点符号进行编码,例如冒号、正斜杠、问号和井号;encodeURI():在查询字符串参数实践中比基本URL编码更常见。兼容性强的替代版本:for(variteminparams){varnowData=params[item];try{params[item]=encodeURIComponent(decodeURIComponent(nowData))}catch(err){varreg=newRegExp(/\%/,"g");params[item]=encodeURIComponent(decodeURIComponent(nowData.replace(reg,"%25")))}}浏览器在%上执行decodeURIComponent时报错