有没有一种方法可以在url中传递javascript变量?

18

有没有办法使下面的脚本将JavaScript值传递到href链接的URL中?

<script type="text/javascript">
function geoPreview(lat,long) {
var elemA = document.getElementById("lat").value;
var elemB = document.getElementById("long").value;

window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=elemA&lon=elemB&setLatLon=Set";

}
</script>
5个回答

44

试试这个:

 window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat="+elemA+"&lon="+elemB+"&setLatLon=Set";

要将变量放入字符串中,请像这样用引号和加号括起变量:

var myname = "BOB";
var mystring = "Hi there "+myname+"!"; 

只需记住这一个规则!


7
不要直接将任意字符串插入URL中,需要使用encodeURIComponent进行正确编码。 - Quentin
这是一个糟糕的做法,请勿在没有适当净化的情况下执行此操作。 - Ray
2
如果这种方式一直被视为不良实践,那么看到正确的做法会很好。 - Garavani

4

您是指在URL的查询字符串中包含JavaScript变量的值吗?

是的:

 window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat="+var1+"&lon="+var2+"&setLatLon="+varEtc;

2
不要直接将任意字符串粘贴到URL中。您需要使用encodeURIComponent进行适当的编码。 - Quentin

4

摘要

使用字符串拼接字符串插值(通过模板字面量)。

这里使用JavaScript模板字面量:

function geoPreview() {
    var lat = document.getElementById("lat").value;
    var long = document.getElementById("long").value;

    window.location.href = `http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=${lat}&lon=${long}&setLatLon=Set`;
}

这两个参数没有被使用,可以删除。

备注

字符串拼接

使用+操作符连接字符串:

window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=" + elemA + "&lon=" + elemB + "&setLatLon=Set";

字符串插值

为了更简洁的代码,使用JavaScript 模板字面量替换表达式并将其转换为字符串表示形式。模板字面量由``包围,占位符用${}包围:

window.location.href = `http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=${elemA}&lon=${elemB}&setLatLon=Set`;

模板字面量自ECMAScript 2015(ES6)起可用。


1

这是设置您的url中的变量的方法

var roomname = '2nxjoinroomnot9480';
window.location.replace("/login?roomid=" + roomname);

在给定页面的URL中,您可以像这样获取变量。
const roomId = new URLSearchParams(window.location.search).get('roomid');
console.log(roomId);

-1

试试这个:

window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=\''+elemA+'\'&lon=\''+elemB+'\'&setLatLon=Set";

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接