javascript XMLHttpRequest 读取外部文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9155960/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 05:46:37  来源:igfitidea点击:

XMLHttpRequest to read an external file

javascripthttpcross-browserxmlhttprequest

提问by federico-t

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

我想通过 JavaScript(在客户端浏览器上运行)检索文本文件中包含的数据(来自给定的 URL)。

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?

但它只适用于 Firefox。有没有人有任何建议可以在每个浏览器中进行这项工作?

Thanks

谢谢

采纳答案by SoWhat

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

它可以xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");在 IE 旧版本中使用。Chrome、Firefox 和所有合理的浏览器都使用 xhr

Frankly, if you want cross browser compatibility, use jquery

坦率地说,如果你想要跨浏览器兼容性,请使用 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})

回答by sakhri Mohamed Amine

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

以前无法使用 XMLHttpRequest 对象上传二进制数据,因为它无法忍受使用 FormData(无论如何当时并不存在)对象。然而,自从新对象和第二版 XMLHttpRequest 的到来,这个“壮举”现在很容易实现

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

很简单,我们只是把我们的 File 对象变成了一个 FormData 对象,然后上传