将变量的值包含在 href 字符串 javascript 中


Including value of a variable to an href string javascript

当我希望将用户重定向到另一个链接时,我有此代码,如下所示:

window.location.href="index.php";

但是,这次我在重定向之前要求用户输入。它是这样的:

var p_value = prompt("Enter value for P");

我希望链接以以下形式构建:

window.location.href="index.php?p=p_value";

页面正在重定向,但链接是索引.php?p=p_value而不是它应该的样子,假设用户输入"10",链接应该是索引.php?p=10

我也尝试过使用

window.location.href="index.php?p=" + p_value;

但仍然不起作用,我该如何解决这个问题?

按给定顺序尝试以下操作:

var p_value = prompt("Enter value for P");
var href_construct = "index.php?p=" + p_value;
p_value != null ? (
    console.log("p_value is blank");
) : (
    console.log("Redirecting");
    window.location.href = href_construct;
);