I have made a feature that takes you to a random link, but i got a lot of links at the moment, and was wondering how i could make javascript read a text file that has all the links.
The code that i have right now does not work, i have tried other similar methods but nothing works.
<script>
var sites = [
function readTextFile("file:///Nicklas Behrend/Desktop/links.txt");
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
];
function randomSite() {
var i = parseInt(Math.random() * sites.length);
location.href = sites[i];
}
</script>
Looks like you have a syntax error. It should probably be this:
var sites = [];
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function () {
if(rawFile.readyState === 4) {
if(rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
alert(allText);
callback(allText);
}
}
}
rawFile.send(null);
}
readTextFile("file:///Nicklas Behrend/Desktop/links.txt", filesText =>{
sites = filesText.split('\n');
});
function randomSite() {
var i = parseInt(Math.random() * sites.length);
location.href = sites[i];
}
You were trying to declare and run the function at the same time, which is all wrong. Also, an XMLHttpRequest()
is async, so you have to have a callback which will return the text.
Once you have that, you can then split the text into an array of sites (I assumed they were newline-delimited in this case).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.