我需要一個純JavaScript函數(對不起,沒有jQuery),它將返回成功的AJAX調用的響應。下面是到目前爲止,我已經得到了功能,我想從響應的HTML返回HTMLobject
:JavaScript函數返回AJAX響應(無jQuery)?
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完成後函數返回對象?
可能重複[如何返回AJAX響應文本?](http://stackoverflow.com/questions/1225667/how-to-return-ajax-response-text) – Quentin 2013-02-28 11:00:02
@Quentin我不想使用任何庫。 – igneosaur 2013-02-28 11:29:19
無論您是否使用圖書館,原則都是一樣的。 – Quentin 2013-02-28 11:47:36