简体   繁体   中英

How to encode URL in JS and Decode in PHP?

Following is my JS code:

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

My question is how do I encode the URL in javascript & decode it in PHP, such that my browser's navigation bar will show

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

instead of

"products.php?price_range=-INFto2000,2001to5000"

and my php code will be able to work with the proper value of -INFto2000,2001to5000 in $_GET['price_range']

You can use encodeURI() This function encodes special characters, except : , / ? : @ & = + $ # : , / ? : @ & = + $ #

To : , / ? : @ & = + $ # : , / ? : @ & = + $ # use encodeURIComponent()

Best way to encode all characters is to run both functions

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

By default php automatically decode Encoded URLs so you don't have to do anything. You can simply access URL parameters like this

 $_REQUEST['price_range'];

For some reasons if you have to decode URL Client side you can use decodeURI() & decodeURIComponent()

Try this in your javascript code

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

You can access the decoded value in $_GET['price_range']. $_GET variables are decoded by default in PHP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM