包含变量值到href字符串javascript

时间:2016-03-06 06:17:16

标签: javascript php hyperlink href

当我希望将用户重定向到另一个链接时,我有这个代码可用,具有以下内容:

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

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

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

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

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

页面被重定向但链接是index.php?p = p_value而不是它应该是什么,假设用户输入'10',链接应该是index.php?p = 10

我也尝试过使用

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

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

1 个答案:

答案 0 :(得分:0)

按给定顺序尝试以下内容:

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;
);