[英]Can't make javascript load .txt file, to load links
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. 我做了一个功能,可以带您到随机链接,但此刻我有很多链接,并且想知道如何使javascript读取包含所有链接的文本文件。
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. 另外,
XMLHttpRequest()
是异步的,因此您必须具有一个将返回文本的回调。
Once you have that, you can then split the text into an array of sites (I assumed they were newline-delimited in this case). 一旦有了它,就可以将文本拆分为多个站点(在这种情况下,我假设它们是用换行符分隔的)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.