在项目开发中,发送ajax请求,给后台传的参数中包含&、#等特殊字符,接口请求失败。解决方法如下:
一、使用encodeURIComponent转码
encodeURIComponent() 函数可把字符串作为 URI 组件进行编码。
该方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ’ ( ) 。
其他字符(比如 :;/?😡&=+$,# 这些用于分隔 URI 组件的标点符号),都是由一个或多个十六进制的转义序列替换的。
代码示例:
let encodeStr=encodeURIComponent(value);
this.$axios
.get("/Shop-name-isrecode?shopName="+encodeStr.trim())
.then(res => {
if (res.Code == 1) {
if(res.Data){
callback(new Error('该商品不存在'));
}else{
callback();
}
}
})
.catch(error => {
console.log(error);
});