开发者

how do i get ajax contents in global javascript variable

开发者 https://www.devze.com 2023-02-09 19:59 出处:网络
i want to put the contents in javascript globaly defined variable, The content i have obtained using ajax call .

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

http://pastebi开发者_StackOverflown.com/TqiJx3PA

thanks for any suggestions


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.

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

精彩评论

暂无评论...
验证码 换一张
取 消