我如何得到全局JavaScript变量的ajax内容全局、变量、内容、JavaScript

2023-09-11 00:43:47 作者:很久没笑了

我希望把在JavaScript globaly定义的变量的内容,我已经使用Ajax调用所获得的内容。

i want to put the contents in javascript globaly defined variable, The content i have obtained using ajax call .

http://pastebin.com/TqiJx3PA

感谢您的任何建议。

推荐答案

该引擎收录code已经这样做了。我猜存在你实际上面临的问题,因为你的Ajax调用是同步,这意味着你正在做的Ajax请求(异步),并立即试图访问值在全局变量 - 但它尚未设置

The pastebin code already does this. I'm guessing that the problem you're actually facing exists because your ajax call is asynchronous, which means that you're making the ajax request (asynchronously), and immediately trying to access the value in the global variable - but it hasn't been set yet.

该解决方案是,以执行后阿贾克斯code。在的onreadystatechange 回调。

The solution to this is to execute your post-ajax code in the onReadyStateChange callback.

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);
}