2013-07-12 156 views
0

我想通過動態地將變量傳遞到URL來動態地將部分添加到URL,如下面的代碼中所示。我怎樣才能獲得下面的代碼工作,使URL找出來是這樣的:動態添加變量到URL

http://www.test.com/test/Test_1/ato.50/[atc1.100/atc2.200/atc3.RandomNumber/atc3.RandomNumber/atc3.RandomNumber/atc4.400 

其中RandomNumber是使用Math.floor(Math.random() * 10 * 10());

(傳遞一個數字的重複,以atc3隨機生成的數字。是故意的)

代碼:

<html> 
<body> 
<script> 
var orderID = 50; 
var Red = 100; 
var Blue = 200; 
var Green = [Math.floor(Math.random() * 10 * 10), Math.floor(Math.random() * 10 * 10), Math.floor(Math.random() * 10 * 10)]; 
var Yellow = 400; 

var tag = '<s'+'cript language="JavaScript" src="http://www.test.com/test/Test_1/ato.' + orderID + '/[atc1.' + Red + '/atc2.' + Blue + '/atc3.' + Green[0]; 

i = 1; 
while (i < Green.length){ 
    var tag_two[i] ='/atc3.' + Green[i]; 
} 
var tag_three ='/atc4.' + Yellow + ']"></s'+'cript>'; 
document.write(tag); 

for (i = 0, i < Green.length, i++){ 
    document.write(tag_two[i]); 
} 
document.write(tag_three); 
</script> 
</body> 
</html> 

謝謝!

+0

這有幫助嗎? http://stackoverflow.com/questions/486896/adding-a-parameter-to-the-url-with-javascript – Ariane

+0

我會看看它,但它比我所知道的要複雜一點。我已經接近我認爲會起作用的地方,我只是無法將URL的三個不同部分加入到一起,以使其起作用。 – Kamui

+0

對不起,我忍不住進一步。你正在做的東西我不太明白(而且太累了,不想嘗試去理解)......我只是認爲把變量放入使用Javascript的URL中最合乎邏輯的方法是讓它將值放入GET ,所以我只是尋找解決方案。如果你的東西有效,那就沒問題。雖然我忍不住想它會製造很奇怪的URL。但這不是問題。 – Ariane

回答

1

而不是創建新的變量傳遞,您必須將字符串concatinate現有變量:

這裏是工作示例http://jsfiddle.net/afsar_zan/aAbD6/

示例代碼

 var orderID = 50; 
     var Red = 100; 
     var Blue = 200; 
     var Green = [Math.floor(Math.random() * 10 * 10), Math.floor(Math.random() * 10 * 10), Math.floor(Math.random() * 10 * 10)]; 
     var Yellow = 400; 
     var i = 0; 
     var tag = '<script language="JavaScript" src="http://www.test.com/test/Test_1/ato.' + orderID + '/[atc1.' + Red + '/atc2.' + Blue + '/atc3.' + Green[0]; 

     while (Green.length>i){ 
     tag += '/atc3.' + Green[i]; 
      i++; 
     } 
     tag +='/atc4.' + Yellow + ']"></s'+'cript>'; 
     alert(tag); 
1

我在代碼中發現了一些問題。所以我糾正了他們,這是你的代碼。

<html> 
<body> 

<script> 
var orderID = 50; 
var Red = 100; 
var Blue = 200; 
var Green = new Array(Math.floor(Math.random() * 10 * 10), Math.floor(Math.random() * 10 * 10), Math.floor(Math.random() * 10 * 10)); 
var Yellow = 400; 

var tag = '<s'+'cript language="JavaScript" src="http://www.test.com/test/Test_1/ato.' + orderID + '/[atc1.' + Red + '/atc2.' + Blue + '/atc3.' + Green[0]; 

i = 1; 
var tag_two=new Array(); 
while (i < Green.length){ 

tag_two[i] ='/atc3.' + Green[i]; 
i++; 
} 

var tag_three ='/atc4.' + Yellow + ']"></s'+'cript>'; 


document.write(tag); 

for (i = 0; i < Green.length; i++){ 

document.write(tag_two[i]); 

} 

document.write(tag_three); 
</script> 

</body> 
</html> 

將變量添加到url的方式似乎是正確的。變量可以通過使用簡單的連接操作符「+」