JavaScript函数返回AJAX响应(没有jQuery)?

时间:2013-02-28 10:58:56

标签: javascript ajax

我需要一个纯JavaScript函数(抱歉,没有jQuery),它将返回成功的AJAX调用的响应。这是我到目前为止所使用的函数,我想从响应中返回带有HTML的HTMLobject

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返回undefined,但我需要它才能工作。有没有办法让函数在AJAX完成后返回对象?

2 个答案:

答案 0 :(得分:1)

不,解决方案就是使用回调函数。

例如:

function getHtml(url, callback) {
    ....
    ....
    callback(HTMLobject); //instead of returning the HTMLobject, call a callback function as pass the `HTMLobject` as a argument.
}

用法:

getHtml('url', function(HTMLobject){
    //Do something with HTMLobject
});

而不是

var HTMLobject = getHtml('url');
//Do something with HTMLobject

发出请求async: false是一个坏主意,因为它会阻止页面直到请求完成(UI不会被重绘并且ui交互不会发生)

答案 1 :(得分:1)

使请求同步,只需执行以下操作

httpRequest.open('GET', url,false);//false make request synchronous 
 httpRequest.send();

“false”选项表示调用是同步的,这意味着代码将挂起,直到响应返回