【问题标题】:Is there a way to pass javascript variables in url?有没有办法在 url 中传递 javascript 变量?
【发布时间】:2023-04-10 19:49:01
【问题描述】:

有没有办法让下面的脚本将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>

【问题讨论】:

    标签: javascript url


    【解决方案1】:

    试试这个:

     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+"!"; 
    

    只要记住一条规则!

    【讨论】:

    • 不要将任意字符串直接粘贴到 URL 中。您需要使用 encodeURIComponent 正确编码它们
    • 这是一种不好的做法,未经适当消毒,请勿执行此操作。
    • 很高兴看到这样做的正确方法,如果这被保留为不好的做法。
    【解决方案2】:

    您的意思是在 URL 的查询字符串中包含 javascript 变量值吗?

    是的:

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

    【讨论】:

    • 不要将任意字符串直接粘贴到 URL 中。您需要使用 encodeURIComponent 正确编码它们
    【解决方案3】:

    总结

    使用字符串连接字符串插值(通过模板文字)。

    这里使用 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) 起可用。

    【讨论】:

      【解决方案4】:

      试试这个:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-02-13
        • 1970-01-01
        • 2012-12-24
        • 1970-01-01
        • 2020-09-02
        • 2021-11-26
        • 2016-03-04
        • 1970-01-01
        相关资源
        最近更新 更多