Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLHttpRequest to read an external file

I want to retrieve the data contained in a text file (from a given URL) through JavaScript (running on the client's browser).

So far, I've tried the following approach:

var xmlhttp, text;
xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'http://www.example.com/file.txt', false);
xmlhttp.send();
text = xmlhttp.responseText;

But it only works for Firefox. Does anyone have any suggestions to make this work in every browser?

Thanks

like image 331
federico-t Avatar asked Mar 12 '26 07:03

federico-t


1 Answers

IT works using xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); in IE older versions. Chrome, Firefox and all sensible browsers use xhr

Frankly, if you want cross browser compatibility, use jquery

its pretty simple there:

var text="";
$.get(url, function(data){text=data;//Do something more with the data here. data variable contains the response})
like image 188
SoWhat Avatar answered Mar 14 '26 21:03

SoWhat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!