简体   繁体   English

如何在javascript中将变量传递给href?

[英]How to pass variable to href in javascript?

How to pass this variable value here?如何在这里传递这个变量值? Below code is not working.下面的代码不起作用。 And all other discussions on Stackoverflow are unclear.关于 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>

And my HTML code is:我的 HTML 代码是:

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

You have to fetch field value using .value as you are passing whole object to the URL as document.getElementbyId('value') returns whole field object.您必须使用.value获取字段值,因为您将整个对象传递给 URL,因为document.getElementbyId('value')返回整个字段对象。

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

So your function should be like this所以你的功能应该是这样的

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

You have fetch value of the field, Currently you are using DOM object您已获取该字段的value ,目前您正在使用 DOM 对象

Use使用

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

OR

Use使用

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

instead of代替

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

Try this:试试这个:

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

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

Try this:试试这个:

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

You have to make some correction in your function..你必须在你的函数中做一些更正..

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.!!');
    }

I use a very different approach to this.我对此使用了一种非常不同的方法。 I set browser cookies in the client that expire a second after I set window.location.href .我在客户端中设置浏览器 cookie,在我设置window.location.href后一秒钟到期。

This is way more secure than embedding your parameters in the URL.这比在 URL 中嵌入参数更安全。

The server receives the parameters as cookies, and the browser deletes the cookies right after they are sent.服务器以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`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM