在带有 XMLHTTPRequest 的现代浏览器中,您的要求非常简单。例如:
function load(url, callback) {
var xhr = new XMLHTTPRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) callback(xhr.responseText);
};
xhr.open("GET", url, true);
}
load("site.com/t.txt", function (contents) {
// contents is now set to the contents of "site.com/t.txt"
});
但是为了确保浏览器与 Internet Explorer 完全兼容,需要更多代码,因为 Internet Explorer 使用 ActiveXObject 而不是 XMLHTTPRequest。
function createXHR() {
if (typeof XMLHTTPRequest === "undefined") {
if (createXHR._version) return new ActiveXobject(createXHR._version);
else {
var versions = [
"Micrsoft.XMLHTTP",
"Msxml2.XMLHTTP",
"Msxml2.XMLHTTP",
"Msxml2.XMLHTTP.3.0",
"Msxml2.XMLHTTP.4.0",
"Msxml2.XMLHTTP.5.0",
"Msxml2.XMLHTTP.6.0"
];
var i = versions.length;
while (--i) try {
var v = versions[i], xhr = new ActiveXObject(v);
createXHR._version = v;
return xhr;
} catch {}
}
} else return new XMLHTTPRequest();
}
function load(url, callback) {
var xhr = createXHR();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) callback(xhr.responseText);
};
xhr.open("GET", url, true);
}
我真的建议使用 jQuery 之类的库来代替这个。欲了解更多信息