最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - XMLHttpRequest to read an external file - Stack Overflow

programmeradmin1浏览0评论

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', '.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

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./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

Share Improve this question asked Feb 6, 2012 at 5:35 federicotfedericot 12.4k19 gold badges69 silver badges111 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

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 patibility, 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})
var xhr = new XMLHttpRequest();
xhr.open('POST', '/uploadFile'); 
var form = new FormData();
form.append('file', fileInput.files[0]);
xhr.send(form);

It was previously impossible to upload binary data with XMLHttpRequest object, because it could not stand the use of FormData (which, anyway, did not exist at that time) object. However, since the arrival of the new object and the second version of XMLHttpRequest, this "feat" is now easily achievable

It's very simple, we just spent our File object to a FormData object and upload it

发布评论

评论列表(0)

  1. 暂无评论