HTML - read .txt file from URL location in javascript

前端 未结 2 793
傲寒
傲寒 2021-01-04 13:14

I want to read a .txt file an URL location, lets say from http://www.puzzlers.org/pub/wordlists/pocket.txt and process its content on my page.

Can you point me out

相关标签:
2条回答
  • 2021-01-04 13:27

    from codegrepper using fetch (unsupported on IE).

    const url = "http://www.puzzlers.org/pub/wordlists/pocket.txt"
    fetch(url)
       .then( r => r.text() )
       .then( t => //process your text! )
    
    0 讨论(0)
  • 2021-01-04 13:29

    this code may help you:

    function getText(){
        // read text from URL location
        var request = new XMLHttpRequest();
        request.open('GET', 'http://www.puzzlers.org/pub/wordlists/pocket.txt', true);
        request.send(null);
        request.onreadystatechange = function () {
            if (request.readyState === 4 && request.status === 200) {
                var type = request.getResponseHeader('Content-Type');
                if (type.indexOf("text") !== 1) {
                    return request.responseText;
                }
            }
        }
    }
    function populateTables(){
        
        var outer_text = getText();
        outer_text = outer_text.split('\n');    // you can adjust the manner of parsing the received file (regexp)
        
        var tableHP = document.getElementById("tHP");
    // Create an empty <tr> element and add it to the 1st position of the table:
        var row = tableHP.insertRow(tableHP.rows.length);
    // Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);
    
    // Add some text to the new cells:
        cell1.innerHTML = outer_text[0];
        cell2.innerHTML = outer_text[1];
    }

    0 讨论(0)
提交回复
热议问题