最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to pass a query parameter along with a redirect in JavaScript - Stack Overflow

programmeradmin5浏览0评论

Right now redirection is made simply by saying

window.location = "/relative_path/";

What I want to do is to add a query parameter along with this redirection, so the destination page can look at that, and after some action was taken it could redirect further to that page.

Example for that use is a login system. When the user's token expires, he is redirected to the login page. At the time of the redirection I want to pass along the exact URL (including query parameters in the URL) to the login page, so after a successful login the user could be redirected back exactly to the point where he/she was.

I tried to pass the path as a URL parameter, but that doesn't work because of escaping issues: the redirect url uses the same characters (?, =, ...), which confuses the system, and the parameters get truncated.

So something like that, but this obviously doesn't work:

window.location = "/login?redirect=/original_location?p1=vl1&p2=v2

Any suggestion is appreciated. I tried encodeURI() but that didn't work.

Right now redirection is made simply by saying

window.location = "/relative_path/";

What I want to do is to add a query parameter along with this redirection, so the destination page can look at that, and after some action was taken it could redirect further to that page.

Example for that use is a login system. When the user's token expires, he is redirected to the login page. At the time of the redirection I want to pass along the exact URL (including query parameters in the URL) to the login page, so after a successful login the user could be redirected back exactly to the point where he/she was.

I tried to pass the path as a URL parameter, but that doesn't work because of escaping issues: the redirect url uses the same characters (?, =, ...), which confuses the system, and the parameters get truncated.

So something like that, but this obviously doesn't work:

window.location = "/login?redirect=/original_location?p1=vl1&p2=v2

Any suggestion is appreciated. I tried encodeURI() but that didn't work.

Share Improve this question edited Jul 18, 2023 at 16:46 Csaba Toth asked Mar 17, 2015 at 6:07 Csaba TothCsaba Toth 10.7k6 gold badges84 silver badges142 bronze badges 1
  • 1 check encodeURIConponent() – Mihai Crăiță Commented Mar 17, 2015 at 6:12
Add a comment  | 

1 Answer 1

Reset to default 16

You can use encodeURIComponent()

The encodeURIComponent() method encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

Example

window.location = "/login?redirect=" + encodeURIComponent("/original_location?p1=vl1&p2=v2")
发布评论

评论列表(0)

  1. 暂无评论