[英]Best way to encode special chars in url
What is the best way to encode special characters in a url? 在网址中编码特殊字符的最佳方法是什么? Let's say I pass an variable from javascript to a php script that way:
假设我以这种方式将变量从javascript传递到php脚本:
http://example.com/my sp3c!al var!a$le
What is the best way to encode that special characters (like whitespace, !, $, /, \\ etc.)? 编码特殊字符(如空格,!,$,/,\\等)的最佳方法是什么? Is there a method in javascript to encode it with a corresponding function in php to decode it there?
javascript中是否有一种方法可以用php中的相应功能对其进行编码以在那里进行解码?
您需要使用encodeURIComponent(yourvar);
You can do it in three ways 您可以通过三种方式做到这一点
encodeURI(yourvar) output http://example.com/my%20sp3c!al%20var!a$le
encodeURI(yourvar)输出
http://example.com/my%20sp3c!al%20var!a$le
amd AMD
encodeURIComponent(yourvar) encodeURIComponent(yourvar)
output http%3A%2F%2Fexample.com%2Fmy%20sp3c!al%20var!a%24le
输出
http%3A%2F%2Fexample.com%2Fmy%20sp3c!al%20var!a%24le
escape() 逃逸()
output http%3A//example.com/my%20sp3c%21al%20var%21a%24le
输出
http%3A//example.com/my%20sp3c%21al%20var%21a%24le
using escape is not recomended because it is deprecated since ECMAScript v3. 建议不要使用转义,因为自ECMAScript v3起已不建议使用转义。
functions is for JavaScript escaping, not HTTP. 函数用于JavaScript转义,而不用于HTTP。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.