如何在JavaScript中将变量传递到href?

14
如何在此处传递变量值?下面的代码不起作用。Stackoverflow上的所有其他讨论都不清楚。
<script type="text/javascript">
        function check()
        {
            var dist = document.getElementById('value');
            if (dist!=""){
                window.location.href="district.php?dist="+dist;
            }
            else
               alert('Oops.!!');
        }
</script>

我的HTML代码如下:

<select id="value" name="dist" onchange="return check()">

您可能也想进行编码。 - Scary Wombat
6个回答

18

由于您正在将整个对象传递到URL中,因此必须使用.value获取字段值,因为document.getElementbyId('value')返回整个字段对象。

var dist = document.getElementById('value').value;

那么你的函数应该像这样

function check() {
    var dist = document.getElementById('value').value; // change here
    if (dist != "") {
        window.location.href = "district.php?dist=" + dist;
    } else
        alert('Oops.!!');
}

6

您已经获取了字段的value,目前您正在使用DOM对象。

请使用

 var dist = document.getElementById('value').value;

使用

 if (dist.value!=""){
     window.location.href="district.php?dist="+dist.value;

替代

if (dist!=""){
     window.location.href="district.php?dist="+dist;

@Joel,我已经为你的问题点赞了,很快你就会有足够的声望来点赞了。就我个人而言,帮助社区成员比声望更重要。圣诞快乐! - Satpal
圣诞快乐,伙计 :) 谢谢 - user3120060

4

试试这个:

function check() {
    var dist = document.getElementById('value').value;

    if (dist) {
        window.location.href = "district.php?dist=" + dist;
    } else {
        alert('Oops.!!');
    }
}

3

试试这个:

var dist = document.getElementById('value').value;
if (dist != "") {
 window.location.href="district.php?dist="+dist;
}

1

你需要在函数中进行一些更正。

function check()
    {
        var dist = document.getElementById('value').value;  //for input text value
       if (dist!==""){  //  for comparision
           window.location.href="district.php?dist="+dist;
       }
       else
           alert('Oops.!!');
    }

1
我对此采用了非常不同的方法。我在客户端设置浏览器cookie,这些cookie在我设置window.location.href一秒钟后过期。
这比将参数嵌入URL要安全得多。
服务器以cookie形式接收参数,并且浏览器在发送完毕后立即删除cookie。
const expires = new Date(Date.now() + 1000).toUTCString()
document.cookie = `oauth-username=user123; expires=${expires}`
window.location.href = `https:foo.com/oauth/google/link`

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