你的位置:首页 > 软件开发 > Java > encodeURIComponent() 函数的使用

encodeURIComponent() 函数的使用

发布时间:2017-11-16 16:00:33
说明:encodeURIComponent() 函数可把字符串作为 URI 组件进行编码。维护项目中,遇到一个登录的问题:(用户的loginName为33195221,密码为147258369+),在密码正确的情况下登录,显示密码错误。于是翻看了代码,看到了登录请求的代码为这样的 ...

encodeURIComponent() 函数的使用

说明:encodeURIComponent() 函数可把字符串作为 URI 组件进行编码。

维护项目中,遇到一个登录的问题:(用户的loginName为33195221,密码为147258369+),在密码正确的情况下登录,显示密码错误。

于是翻看了代码,看到了登录请求的代码为这样的:

$("#login").click(function() { var userName = $("#userName").val(); var password = $("#password").val();     var url = basePath + '/user/user_login.do'; url = url + '?user.userName=' + userName + '&user.password=' + password; $.ajax({   url : url,    dataType : 'json',   type : "post",  success : function(data) {   if (data.resultStatus == 'ok') {    window.location.href='index.html';   }else{    alert('登录失败');   }  },  error : function() {   alert("未能连接到服务器!");  }  });});

访问的url:

encodeURIComponent() 函数的使用

看着没问题,但是传到后台后,明显后面的特殊字符“+”号变成了空格,如下图:

encodeURIComponent() 函数的使用

所以,登录的时候就显示密码错误。

解决办法:

像这种url中带有特殊字符的情况下,就用encodeURIComponent() 函数,把要编码的字符串传进去,比如,刚开始的js代码中的url关于密码的那块,可以这样改:

url = url + '?user.userName=' + userName + '&user.password=' + encodeURIComponent(password);
这样就不会把传过去的特使字符“+”变为空格了。


注:encodeURIComponent不编码字符有71个:!, ',(,),*,-,.,_,~,0-9,a-z,A-Z

 

原标题:encodeURIComponent() 函数的使用

关键词:函数

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。