2012-01-07 80 views
3

我想在URL中傳遞2個變量值,該URL將被重定向後。我如何將它們插入到JavaScript字符串中?如何通過url傳遞2個JavaScript變量?

我:

var a = document.getElementById("username_a").value; 
var b = document.getElementById("username_b").value; 

,並希望類似:var string_url = "http://www.example.com/?{a}blabla={b}",然後重定向莫名其妙。

在PHP中我會爲例子代碼去:<iframe src="http://www.example.com?query=<?php echo $the_variable;?>">

回答

0

使用的符號拆分瓦爾

var string_url = "http://www.example.com/?" + "username_a=" + a + "&username_b=" + `b 

可以作出更sopisticated,但在本質上是你所需要的

+0

這是用戶輸入。數據**需要**轉義或它會中斷。 – Quentin 2012-01-07 11:31:05

0

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; 
6

您可以在JavaScript字符串添加,"a" + "b" == "ab"評估爲true

所以,你想要什麼可能是var string_url = "http://www.example.com/?" + a + "&blabla=" + b;

但你應該永遠逃脫瓦爾特別是如果他們來自input S,所以儘量

a = encodeURIComponent(a); 
b = encodeURIComponent(b); 

然後

var string_url = "http://www.example.com/?" + a + "&blabla=" + b; 

將您重定向可以使用window.location

window.location = string_url;