将变量动态添加到URL

Dynamically adding variables to a URL

本文关键字:URL 添加 动态 变量      更新时间:2023-09-26

我正试图通过将变量动态传递到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>

谢谢!

您不需要创建新变量,而是必须将字符串连接到现有变量:

这是一个工作示例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);

我在您的代码中发现了一些问题。所以我已经纠正了它们,这是你的代码。

<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添加变量的方式似乎是正确的。变量可以通过使用简单的连接运算符"+"来传递