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()">
4

6 回答 6

18

.value当您将整个对象传递给 URL 作为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.!!');
}
于 2013-12-25T05:22:17.010 回答
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;
于 2013-12-25T05:22:05.353 回答
4

尝试这个:

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

    if (dist) {
        window.location.href = "district.php?dist=" + dist;
    } else {
        alert('Oops.!!');
    }
}
于 2013-12-25T05:24:17.817 回答
3

尝试这个:

var dist = document.getElementById('value').value;
if (dist != "") {
 window.location.href="district.php?dist="+dist;
}
于 2013-12-25T05:24:44.020 回答
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.!!');
    }
于 2013-12-25T05:25:43.683 回答
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`
于 2021-02-08T22:47:24.750 回答