当他们按下带有JavaScript / jQuery的按钮时,我一直在寻找一种方法将用户带到随机页面。我见过的所有内容都包含数组中的所有页面,然后使用脚本随机选择索引。
是否可以在不将所有页面添加到数组中的情况下执行此类操作。我不想坐在那里将目录中的每个页面/图像添加到一个大型数组然后运行脚本,我只是希望它通过appache目录列表并自行抓取。
可以这样做吗?我知道我们应该包含我们迄今为止的代码,但这更像是一个概念性问题。
答案 0 :(得分:3)
使用ajax
获取您的链接:
$.ajax({
method: "GET",
url: "/getRandomLink", // I don't know which server side language you're using, I presume its PHP
dataType: "text", // text will be enought if it only returns a link
success: function(link) {
window.location.href = link;
}
});
然后把它放在你选择的事件中。很好,很容易。
<强>更新强>
您的服务必须是带有链接的字符串。我说你正在使用PHP,所以会像:
<?php
$randomLink = "";// Code to get the random link here
echo $randomLink; // e.g.: http://www.google.com/
?>
答案 1 :(得分:1)
Something 需要提供脚本随机选择的文件列表。这将是一个预生成的数组或一个ajax请求。
这些可行:
...但是出于您的目的,您的服务器端脚本只返回一个随机选择的文件更有意义,而不是仅为客户端使用带宽来丢弃除一个以外的所有文件。
答案 2 :(得分:0)
编辑以反映OP给出的评论。请原谅jQuery。
假设您获得的目录索引是标准的Apache Auto-Index页面:
//jQuery doc.ready, because I'm too lazy to do something better ;)
$(function () {
var links = [];
$.ajax(
{
//url: location.pathname, // Use current page
url: '/directoryname/', //directory index of your choice
success: saveAjaxedLinks
}
);
function saveAjaxedLinks (data, e) {
// Scrape anchors off of page.
// Note -- there might be other anchors on the page
// that you don't want to pick up, say the "up a directory level" anchors.
// you can filter those out if you want, but you'll have to determine the criteria for doing so.
var directory = $('a', data);
//Get anchor nodes and store them.
links = directory.get();
//Assign event listener to button after the data is ready.
$('button#yourbuttonid').on( 'click', onclickGetRandomPage );
//uncomment to do action immediately.
//onclickGetRandomPage();
}
function onclickGetRandomPage (e) {
if ( !!e && !!e.preventDefault ) {
e.preventDefault();
}
//if no links on the index, do nothing.
if ( !links.length ) return;
//Get the a random index from the links.
var rnd = Math.floor( Math.random()*links.length);
for (var i = 0, len = links.length; i < len; i++ ) {
// Make sure there's an actual href inside the random link.
// Also, check to make sure the links arent just hashes. Not necessary if you're just using an apache auto-index.
// If there are certain types of links you don't want (eg. directory roots), you can filter them out here.
if ( !!links[rnd].href && links[rnd].href.replace( links[rnd].hash, '' ) !== (location.href.replace( location.hash, '' ) ) ) {
//console.log(links[rnd].href); //Log out the links if you're just testing
window.location.href = links[rnd].href;
break;
} else {
//That link was no good, get a different one.
rnd = Math.floor( Math.random()*links.length );
}
}
}
});