简体   繁体   中英

Randomly pick a line and save each word on that line into each Javascript variable

pick a line depending on variable "number" then save each of the words on that line into each javascript variable1 and javascript variable2.

if variable number equals 2, pick line 2, set Variables1 to potato ,and set Variables2 to tomato.

//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); 

What should I do next?

Any help is appreciated Thanks in advance

You better off chosing random string via your backend server rather than js because servers meant to do that. You could create a page to which you will reffer to and pass path to your file as parameter and set it to return random line from that file. After you parsed that string you can use split() onto your parsed string to get an array of those words. Also you should consider using fetch 'cause it's a replacement for a XHR .

So my js code looks something like this:

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');
        }
    });
}

And then on a backend it looks like that:

$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;
        }
    }
}

Although not every browser supports fetch and if you want to support more browsers you'll need polyfill.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM