一个朋友正在从他的网站链接到我的页面。
由于我需要用户在访问我的页面时避免缓存,所以我希望url具有以下形式:
http://www.mypage.com/index.php?456646556
其中456646556是随机数。
由于我的朋友没有安装php,我该如何使用Javascript构建带有随机数的链接?
此外,我的朋友要求我只给他URL,没有其他功能,因为他的页面已经加载了这些功能。这可行吗?
非常感谢。
http://www.mypage.com/index.php?456646556
其中456646556是随机数。
由于我的朋友没有安装php,我该如何使用Javascript构建带有随机数的链接?
此外,我的朋友要求我只给他URL,没有其他功能,因为他的页面已经加载了这些功能。这可行吗?
非常感谢。
我会添加一个参数,但如果不需要可以将其省略:
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)
<a href="http://www.mypage.com/index.php?" onclick="this.href+=new Date().getTime();return true;">link</a>
var lower = 0;
var upper = 100000000;
var url = "http://www.mypage.com/index.php?"+(Math.floor(Math.random()*(upper-lower))+lower)
它生成一个从0(下限)到100000000(上限)的随机X,你可以自己设置边界;)
// navigate to the new page and append a random number at the end of the url
window.location.href = newUrl + '?' Math.random();
注意,你可能会从Math.random
获得相同的输出两次,毕竟它是随机的。