AJAX中如何传输中文参数的编码问题
Ajax中使用Post提交中文及参数传递时,如果直接使用的是中文参数,这时在后台解析request便得不到中文;或者产生中文参数乱码的问题。那么,此时就要用中js中的字符转码函数encodeURIComponent() ,然后在PHP服务器端使用rawurldecode函数解码即可使用。
例如:我们这里传输AJAX中的URL为var url=”./?a=orderQuerys&u=”+encodeURIComponent(userName)+”&n=”+encodeURIComponent(shipName)+”";在后台服务器接收时这样写:$name=rawurldecode($request['u'])就可以了。
注:JS中,在使用字符转码的时候,推荐使用 encodeURIComponent() 或者 encodeURI(),而非escape()。原因在于,escape() 只是为 ASCII字符 做转换工作,转换成的 %unnnn 这样的码,如果要用更多的字符如 UTF-8字符库就一定要用 encodeURIComponent() 或 encodeURI() 转换才可以成 %nn%nn 这的码才可以。
js:encodeURIComponent —— decodeURIComponent;php: rawurlencode —— rawurldecode
(两者的编码和解码是可以通用的,目前只发现“•—”两个例外)。
If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments
还没有评论。
发表评论