JavaScript:包含随机数的网址

8
一个朋友正在从他的网站链接到我的页面。 由于我需要用户在访问我的页面时避免缓存,所以我希望url具有以下形式:

http://www.mypage.com/index.php?456646556

其中456646556是随机数。

由于我的朋友没有安装php,我该如何使用Javascript构建带有随机数的链接?

此外,我的朋友要求我只给他URL,没有其他功能,因为他的页面已经加载了这些功能。这可行吗?

非常感谢。

4个回答

20

我会添加一个参数,但如果不需要可以将其省略:

var url = "http://www.mypage.com/index.php?rnd="+Math.random()

或者

var url = "http://www.mypage.com/index.php?rnd="+new Date().getTime()

链接:

<a href="http://www.mypage.com/index.php?rnd=1" onClick="this.href=this.href.split('?')[0]+'?rnd='+new Date().getTime()">Mostly random</a>

请注意,如果您有多个任务 - 例如在循环中,您需要添加到getTime,因为循环的迭代速度比毫秒快:

var rnd = new Date().getTime();
for (var i=0;i<links.length;i++) {
   links[i].href = "http://www.mypage.com/index.php?rnd="+(rnd+i);
}

更新:使用带有searchParams的URL构造函数

const addRnd = urls => {
  let rnd = new Date().getTime();
  return urls.map((urlStr,i) => {
    let url = new URL(urlStr);
    url.searchParams.set("rnd",rnd+i);  // in case called multiple times
    return url;
  });
};
const urls = addRnd( ["http://www.mypage.com/index1.php","http://www.mypage.com/index2.php","http://www.mypage.com/index3.php"])
console.log(urls)


3
<a href="http://www.mypage.com/index.php?" onclick="this.href+=new Date().getTime();return true;">link</a>

每次单击它都会添加一个新日期。这就是为什么我在我的建议中使用了split的原因。 - mplungjan
我以为对于只需要点击几次的情况来说这是可以的。如果你期望某人频繁点击该链接,那么你就必须使用分割函数。 - igor

2
var lower = 0;
var upper = 100000000;
var url = "http://www.mypage.com/index.php?"+(Math.floor(Math.random()*(upper-lower))+lower)

它生成一个从0(下限)到100000000(上限)的随机X,你可以自己设置边界;)


0
使用 Math.random()
 // navigate to the new page and append a random number at the end of the url
 window.location.href = newUrl + '?' Math.random();

注意,你可能会从Math.random获得相同的输出两次,毕竟它是随机的。


document.location已被废弃,使用document.URL请使用window.location。 - mplungjan
@mplungjan 刚醒来,已经修好了 :) - Ivo Wetzel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接