1

I have this code to randomly grab a file from a folder path, and load it via jQuery:

var path = '/path-to-files/',
files = ['1.php', '2.php', '3.php', '4.php', '5.php', '6.php'],
i = Math.floor(Math.random()*files.length);
var url = (path+files[i]);
$("#my-div").load(url);

It's great, it works well. But I would prefer a method to randomly grab files from the path without building an array. Is that possible?

3 Answers 3

5

You can't get a list of files from a directory using just JavaScript(jQuery is JavaScript), it would have to be handled from the server. You could request a server-file that then returns the content of a random file from a directory.

Sign up to request clarification or add additional context in comments.

Comments

5
var i = Math.floor(Math.random() * 6) + 1;
$("#my-div").load('/path-to-files/' + i + '.php');

7 Comments

What if I did not want to specify a max limit on files (in this example, 6)?
@Yahreen: You mean a random number from 1 to Infinity?
This is just as hardcoded as what he had in the original question.
@Yahreen: You're saying you want filenames from the server without having a collection present in the scripting environment?
@user1689607 yes, it sounds like I will need a server solution for my problem. Thank you.
|
1

You'll need to make a server request to get the array of possible files. This is the only way to do this without sticking to a naming convention or a set list of files.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.