如何在JS中编码URL并在PHP中解码


How to encode URL in JS and Decode in PHP?

下面是我的JS代码:

window.location.href = 'products.php?price_range=-INFto2000,2001to5000';

我的问题是如何用javascript&用PHP解码,这样我浏览器的导航栏就会显示

"products.php?price_range=-INFto2000%2C2001to5000"

而不是

"products.php?price_range=-INFto0002001to5000"

我的php代码将能够在$_GET['price_range'] 中使用正确的-INFto2000,2001to5000

您可以使用encodeURI()此函数编码特殊字符,: , / ? : @ & = + $ # 除外

: , / ? : @ & = + $ #使用encodeURIComponent()

对所有字符进行编码的最佳方式是运行两个功能

var url = 'products.php?price_range=-INFto2000,2001to5000';
url = encodeURI(url);// Encode special characters
url = encodeURIComponent(url);//Encodes : , / ? : @ & = + $ # characters

默认情况下,php会自动decode编码URL,这样您就不必做任何事情。你可以简单地访问像这样的URL参数

 $_REQUEST['price_range'];

由于某些原因,如果你必须解码URL客户端,你可以使用decodeURI()&decodeURIComponent()

在您的javascript代码中尝试此操作

window.location.href = 'products.php?price_range='+encodeURIComponent('-INFto2000,2001to5000');

您可以访问$_GET['price_range']中的解码值$_GET变量在PHP中默认解码。