XMLHttpRequest读取外部文件 [英] XMLHttpRequest to read an external file

查看:127
本文介绍了XMLHttpRequest读取外部文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

到目前为止, ve尝试了以下方法:

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;

但它只适用于Firefox。

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

感谢

推荐答案

IT在IE旧版本中使用 xmlhttp = new ActiveXObject(Microsoft.XMLHTTP); Chrome,Firefox和所有合理的浏览器使用xhr

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

坦白地说,如果你想要跨浏览器兼容性,请使用jquery

Frankly, if you want cross browser compatibility, use jquery

它很简单:

var text="";
$.get(url, function(data){text=data;//Do something more with the data here. data variable contains the response})

这篇关于XMLHttpRequest读取外部文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆