使用Javascript读取文本文件到数组

时间:2014-07-31 17:46:54

标签: javascript

我正在使用javascript将txt文件读取到数组中但是当我document.write(lineArr[2]);时,我没有在屏幕上打印任何内容。

当我执行console.log(lineArr);时,console.

没有任何结果

这是我的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

这是我的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]);
}

1 个答案:

答案 0 :(得分:0)

如果您想在纯JavaScript中执行此操作,则以下内容应该有效。我通过添加成功和错误回调函数来模仿jQuery。这应该可以重复使用。

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

状态代码0:

请参阅HTTP status code 0 - what does this mean in MS XMLHTTP?


如果您选择使用jQuery,您只需要替换第一行:

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

使用:

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