首页 > 解决方案 > 随机选择一行并将该行上的每个单词保存到每个 Javascript 变量中

问题描述

根据变量“数字”选择一行,然后将该行上的每个单词保存到每个 javascript 变量 1 和 javascript 变量 2 中。

如果变量数等于 2,则选择第 2 行,将变量 1 设置为土豆,将变量 2 设置为番茄。

//Text file on server 

Apple, Oranges
Potato, Tomato
Cake, Muffin
Cheese, Milk



//Java script code in browser. 
    var number = Math.floor((Math.random() * 4) + 1);
    var xhr = new XMLHttpRequest();
    xhr.open("GET","http://..........data.txt",false);
    xhr.send(null); 

接下来我该怎么办?

任何帮助表示赞赏提前谢谢

标签: javascripttext

解决方案


您最好通过后端服务器而不是 js 选择随机字符串,因为服务器就是这样做的。您可以创建一个您将参考的页面并将路径作为参数传递给您的文件,并将其设置为从该文件返回随机行。解析该字符串后,您可以使用split()解析的字符串来获取这些单词的数组。此外,您应该考虑使用fetch'cause 它是XHR.

所以我的js代码看起来像这样:

function getTextFile(path){
    var line = Math.floor(Math.random() * 4);
    params = {
        path: path,
        line: line
    }

    var data = new FormData();
    data.append("json", JSON.stringify(params));

    var promise = fetch("http://mysite/myscript.php", {method: 'POST', body: data})
    .then((response) => {
        return response.text();
    }).then((text) => {
        if(text != 'error'){
           text = text.replace(/(\r\n|\n|\r)/gm, "");
           var result = text.split(" ");
           //Result will be an array of those values and will look something   like that:
           //["Cheese", "Milk", "Yogurt"]
        }
        else{
           alert('error');
        }
    });
}

然后在后端它看起来像这样:

$json = (array) json_decode($_POST['json']);


if( validatePath($json['path']) ){
    $file = file($json['path']);
    $my_string = $file[$json['line']];
    echo $my_string;
}
else{
    echo 'error';
}


function validatePath($path){
    //You should definitely use some other validations
    $allowedExtensions = ['txt', 'json'];
    $pathinfo = pathinfo($path);
    //Right now it's only checking for right extension and 
    //that's this file ain't located in admin subdir
    if(strstr($pathino['dirname'], '/admin') || !in_array($pathinfo['extension'], $allowedExtensions)){
        return false;
    }
    else{
        //Check if file exists
        if( file_exists($path) ){
            return true;    
        }
        else{
            return false;
        }
    }
}

虽然不是每个浏览器都支持fetch,如果你想支持更多的浏览器,你需要 polyfill。


推荐阅读