小编典典

我如何在全局javascript变量中获取Ajax内容

ajax

我想将内容放入javascript全局定义的变量中,我使用ajax call获得的内容。

http://pastebin.com/TqiJx3PA

感谢您的任何建议


阅读 273

收藏
2020-07-26

共1个答案

小编典典

pastebin代码已经做到了。我猜您实际上面临的问题是存在的,因为您的ajax调用是 异步的
,这意味着您正在(异步)发出ajax请求,并立即尝试访问全局变量中的值-但它尚未尚未设定。

解决方案是在onReadyStateChange回调中执行后ajax代码。

function handleResponse(result_cont) {
    // your result_cont processing code here
}

ajax(handleResponse);

function ajax(callback) {
    var xmlHttp;
    try { // Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    } catch (e) {
        // Internet Explorer
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                return false;
            }
        }
    }
    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4) {
            if (xmlHttp.responseText != "") {
                result_cont = xmlHttp.responseText
                alert(result_cont);

                // ############# here's the important change #############
                // execute the provided callback
                callback(result_cont);
            }
        }
    }
    xmlHttp.open("GET", "contentdetails.php?cid=1", true);
    xmlHttp.send(null);
}
2020-07-26