Reputation: 667
I have just started getting into Javascript and mobile web programming. One thing that I am uncertain of is how I can write proper code that runs on any browser without having the end user have any extra requirements on their end (what browser to use).
I am coding this in google chrome and more recently in c9.io.
I thought this would work:
function readTextFile(file)
{
var client = new XMLHttpRequest();
client.open('GET', file);
client.send();
client.onreadystatechange = function() {
alert(client.responseText);
}
}
But i get the error that XMLHTTpRequest is not defined. I have been trying to figure out why this is and I keep coming to different browsers not supporting this. I had figured simple file io would not be that difficult but its causing me more trouble than I had hoped.
What is the best way to input a text file? It is 1 text file that is not having anything being written to it. Just read only. The end user isn't choosing this text file it should be the only option.
Upvotes: 2
Views: 2881
Reputation: 9235
The order in your code is wrong, send
method should be the last one; otherwise, your code is fine and it should work fine in all modern browsers. The mentioned order issue, or maybe was something else (before) causing that error. The snippet below will also split received text in an array of text lines
var xhr, i, text, lines;
if(window.XMLHttpRequest){
// IE7+, Firefox, Chrome, Opera, Safari
xhr = new XMLHttpRequest();
}else{
// IE5, IE6 - next line supports these dinosaurs
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
text = xhr.responseText;
lines = text.split("\n");
for(i = 0; i < lines.length; i++){
console.log(lines[i]);
}
}
}
xhr.open('GET', 'http://domain/file.txt', true);
xhr.send();
Upvotes: 1
Reputation: 488
XMLHTTpRequest is not supported by the older browsers. Try doing this to support the older browsers as well:
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
Upvotes: 0