1

我需要一个纯 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 完成后返回对象?

4

2 回答 2

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 交互也不会发生)

于 2013-02-28T11:00:13.047 回答
1

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

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

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

于 2013-02-28T11:03:09.043 回答