简体   繁体   English

使用Javascript将txt文件读取到数组

[英]Reading txt File To Array With Javascript

I am reading a txt file to an array with javascript but when I document.write(lineArr[2]); 我正在使用javascript将txt文件读取到数组,但是当我document.write(lineArr[2]); I get nothing printing to the screen. 我什么都没打印到屏幕上。

When I do console.log(lineArr); 当我做console.log(lineArr); I get nothing to the console. 我什么都没拿到console.

This is my txt file format, 这是我的txt文件格式,

test1@test.com 
test2@test.com
test3@test.com
test4@test.com
test5@test.com
test6@test.com
test7@test.com
test8@test.com
test9@test.com
test10@test.com

And this is my JavaScript: 这是我的JavaScript:

// This will read file and send information to other function
function getData() {
    var xmlhttp;

    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
            var lines = xmlhttp.responseText;

            intoArray(lines);
        }
    }

    xmlhttp.open("GET", "text.txt", true);
    xmlhttp.send();
}

function intoArray(lines) {
    var lineArr = lines.split('\n');

    // Just to check if it works output lineArr[index] as bellow*
    document.write(lineArr[2]);
    document.write(lineArr[3]);
}

If you want to do this in plain JavaScript, the following should work. 如果要使用纯JavaScript进行此操作,则应执行以下操作。 I mimicked jQuery a bit by adding success and error callback functions. 我通过添加成功和错误回调函数来模仿jQuery。 This should make this reusable. 这应该可以重用。

getData('text.txt', 'text', handleSuccess, handleError);

function handleSuccess(data) {
    intoArray(data);
}

function handleError(xmlhttp, statusText, errorText) {
    document.write('Error: ' + errorText);
}

// This will read file and send information to other function
function intoArray(lines) {
    var lineArr = lines.split('\n');

    // Just to check if it works output lineArr[index] as bellow*
    document.write(lineArr[2]);
    document.write(lineArr[3]);
}

// Reusable code below, only needed without jQuery.

function createXMLHttpRequest() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else {
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
}

function getErrorText(xmlhttp) {
    if (xmlhttp.status === 0) {
        return 'Not connected.\nVerify Network.';
    } else if (xmlhttp.status == 404) {
        return 'Requested page not found. [404]';
    } else if (xmlhttp.status == 500) {
        return 'Internal Server Error [500].';
    } else if (exception === 'parsererror') {
        return 'Requested JSON parse failed.';
    } else if (exception === 'timeout') {
        return 'Time out error.';
    } else if (exception === 'abort') {
        return 'Ajax request aborted.';
    } else {
        return 'Uncaught Error.\n' + xmlhttp.responseText;
    }
}

function getData(url, responseType, successHandler, errorHandler) {
    var xmlhttp = createXMLHttpRequest();

    xmlhttp.responseType = responseType;

    xmlhttp.onreadystatechange = function() {
        switch (xmlhttp.readyState) {
            case 4:
                var status = xmlhttp.status;

                if (xmlhttp.response === '') {
                    status = -1;
                }
                switch (status) {
                    case 0: // SEE EXPLANATION BELOW
                    case 200:
                        successHandler(xmlhttp.response, xmlhttp.statusText, xmlhttp);
                        break;
                    default:
                        errorHandler(xmlhttp, xmlhttp.statusText, getErrorText(xmlhttp))
                }
                break;
            default:
                break;
        }
    }

    // void open(DOMString method, DOMString url, boolean async)
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

Status Code 0: 状态码0:

Refer to HTTP status code 0 - what does this mean in MS XMLHTTP? 参考HTTP状态代码0-这在MS XMLHTTP中是什么意思?


If you choose to use jQuery, all you have to do is replace the first line: 如果您选择使用jQuery,那么您要做的就是替换第一行:

getData("text.txt", 'text', handleSuccess, handleError);

With: 附:

$(document).ready(function() {
    $.ajax({
        url: 'text.txt',
        dataType: 'text',
        success: handleSuccess,
        error: handleError
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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