If you want to do this in plain JavaScript, the following should work. I mimicked jQuery a bit by adding success and error callback functions. 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:
Refer to HTTP status code 0 - what does this mean in MS XMLHTTP?
If you choose to use jQuery, all you have to do is replace the first line:
getData("text.txt", 'text', handleSuccess, handleError);
With:
$(document).ready(function() {
$.ajax({
url: 'text.txt',
dataType: 'text',
success: handleSuccess,
error: handleError
});
});