javascript - 如何在 URL 中传递值并在新 URL 中插入值以使用 Javascript 进行重定向?

标签 javascript url redirect parameters

我在 URL 中传递一个值,格式为 http://example.com/page?id=012345 。然后需要将传递的值插入到新的 URL 中并将页面重定向到新的 URL。这是我一直在研究的内容

function Send() {
    var efin = document.getElementById("id").value;
    var url = "https://sub" + encodeURIComponent(efin) + ".example.com" ;
    window.location.href = url;
};    

最佳答案

听起来您正在寻找 URLSearchParams 的功能- 具体使用.get()从 URL 获取特定参数

// Replacing the use of 'window.location.href', for this demo
let windowLocationHref = 'http://example.com/page?id=012345';

function Send() {
    let url = new URL(windowLocationHref);
    let param = url.searchParams.get('id');

    let newUrl = "https://sub" + encodeURIComponent(param) + ".example.com" ;
    
    console.log('Navigate to: ' + newUrl);    
    //window.location.href = newUrl;
};

Send();

关于javascript - 如何在 URL 中传递值并在新 URL 中插入值以使用 Javascript 进行重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59634106/

相关文章:

.htaccess - 所有网站上的 Magento HTTPS : urls redirect to homepage

javascript - 使用 JS 创建 SVG 元素(错误?)

javascript - 基于带参数的正则表达式生成字符串

javascript - jQuery 克隆一个带有 active 类的图像并将其设置为 div 的背景图像

facebook - FB Like 按钮计数器不断消失

.htaccess - 将所有请求重定向到 index.php 而无需直接访问

javascript - MutationObserver 的 DOM 上下文丢失,因为它触发得太晚

php - 检查查询字符串是否存在,如果不存在则创建一个 - PHP

c# - 数字后修剪字符串

Javascript 页面重新路由