我需要一个纯 JavaScript 函数(抱歉,没有 jQuery),它将从成功的 AJAX 调用返回响应。这是到目前为止我得到的函数,我想HTMLobject
从响应中返回带有 HTML 的函数:
function getHtml(url) {
var httpRequest;
var HTMLobject;
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!httpRequest) {
console.error('Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
// OK, turn the string into HTML.
var div = document.createElement('div');
div.innerHTML = httpRequest.responseText;
// Assign the converted HTML to HTMLobject.
HTMLobject = div.childNodes[0];
} else {
console.debug('There was a problem with the request.');
}
}
};
httpRequest.open('GET', url);
httpRequest.send();
return HTMLobject;
}
我知道为什么,HTMLobject
返回未定义,但我需要它工作。有没有办法让函数在 AJAX 完成后返回对象?