Javascript: url containing random number

淺唱寂寞╮ 提交于 2019-11-29 10:12:26

I would add a parameter but you can leave it out if needed:

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

or

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

Link:

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

Note that if you have more than one assignment - for example in a loop, you need to add to the getTime since an iteration of the loop is faster than a millisecond:

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);
}
var lower = 0;
var upper = 100000000;
var url = "http://www.mypage.com/index.php?"+(Math.floor(Math.random()*(upper-lower))+lower)

it generates a random X from 0(lower) to 100000000 (upper), you can obv set the bounds you want ;)

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

Use Math.random():

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

Beware you might get the same output twice from Math.random, after all it's random.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!