如何通过 url 传递 2 个 JavaScript 变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8769303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass 2 JavaScript variables through a url?
提问by a.litis
I am trying to have 2 variable values passed in a url, which url will be redirected after. How can I insert them in a JavaScript string?
我正在尝试在 url 中传递 2 个变量值,该 url 将在之后重定向。如何将它们插入到 JavaScript 字符串中?
I have:
我有:
var a = document.getElementById("username_a").value;
var b = document.getElementById("username_b").value;
and want something like: var string_url = "http://www.example.com/?{a}blabla={b}"
and then redirect somehow.
并想要类似的东西: var string_url = "http://www.example.com/?{a}blabla={b}"
然后以某种方式重定向。
In PHP I would go with that code for example: <iframe src="http://www.example.com?query=<?php echo $the_variable;?>">
在 PHP 中,我会使用该代码,例如: <iframe src="http://www.example.com?query=<?php echo $the_variable;?>">
回答by Matmarbon
You can add strings in JavaScript, "a" + "b" == "ab"
evaluates to true
.
您可以在 JavaScript 中添加字符串,"a" + "b" == "ab"
计算结果为true
.
So what you want is probably var string_url = "http://www.example.com/?" + a + "&blabla=" + b;
所以你想要的可能是 var string_url = "http://www.example.com/?" + a + "&blabla=" + b;
But you should ever escape vars especially if they come from input
s, so try
但是你应该永远逃避 vars,特别是如果它们来自input
s,所以尝试
a = encodeURIComponent(a);
b = encodeURIComponent(b);
And then
进而
var string_url = "http://www.example.com/?" + a + "&blabla=" + b;
To redirect you can use window.location
:
要重定向,您可以使用window.location
:
window.location = string_url;
回答by gotofritz
use the ampersand to split vars
使用与号来分割变量
var string_url = "http://www.example.com/?" + "username_a=" + a + "&username_b=" + `b
Could be made more sopisticated, but that in essence is what you need
可以做得更复杂,但这本质上就是你所需要的
回答by Quentin
JavaScript doesn't do string interpolation. You have to concatenate the values.
JavaScript 不进行字符串插值。您必须连接这些值。
var uri = "http://example.com/?" + encodeUriComponent(name_of_first_variable) + "=" + encodeUriComponent(value_of_first_variable) + '&' + encodeUriComponent(name_of_second_variable) + "=" + encodeUriComponent(value_of_second_variable);
location.href = uri;