简体   繁体   English

JavaScript 重定向,同时将参数传递给新的 URL

[英]JavaScript redirect while passing on the parameter to new URL

Im trying to write the code for a javascript that will redirect to a new url while fetching the url parameter and passing it to the new url.我正在尝试为 javascript 编写代码,它将重定向到新的 url,同时获取 url 参数并将其传递给新的 url。

The visited url = www.example.com/files/?id=12345访问过的 url = www.example.com/files/?id=12345

New Url to redirect to = www.sample.com/files/?list=12345新 Url 重定向到 = www.sample.com/files/?list=12345

This is the below code i have been able to come up with.这是我能够想出的以下代码。

<!DOCTYPE html>
<html>
<body>

<script>
const urlParams = new URLSearchParams(window.location.search);
const id = urlParams.get('id');

window.location.href = `www.sample.com/files/?list=${id}`;

</script>

</body>
</html>

your code works well, but when using window.location.href to redirect, the browser by default asumes that the url you are using is relative to the current site, so if you redirect to "sample.com" you are going to end up in "example.com/sample.com"您的代码运行良好,但是当使用 window.location.href 进行重定向时,默认情况下浏览器假定您使用的 url 是相对于当前站点的,因此如果您重定向到“sample.com”,您将结束在“example.com/sample.com”

So to force the browser to redirect to another site you need to include the full URL with the protocol "https://sample.com"因此,要强制浏览器重定向到另一个站点,您需要使用协议“https://sample.com”包含完整的 URL

So the fixed code would be所以固定代码是

<!DOCTYPE html>
<html>
<body>

<script>
const urlParams = new URLSearchParams(window.location.search);
const id = urlParams.get('id');

window.location.href = `https://www.sample.com/files/?list=${id}`;

</script>

</body>
</html>

Note that Im using https, if your site does not have https, change it for http or you are gonna get an error from the browser (and try to get https jeje)请注意,我使用的是 https,如果您的站点没有 https,请将其更改为 http,否则您会从浏览器中收到错误消息(并尝试获取 https jeje)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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