0

I am trying to make an AJAX JavaScript class, code like this:

// Create a new User object that accept an object of properties
function JsonLoader() {

    function ajaxRequest() {
        var activexmodes = ["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"]; //activeX versions to check for in IE
        if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
            for (var i=0; i<activexmodes.length; i++) {
                try {
                    return new ActiveXObject(activexmodes[i]);
                }
                catch(e) {
                    //suppress error
                }
            }
        }
        else if (window.XMLHttpRequest) // if Mozilla, Safari etc
            return new XMLHttpRequest();
        else
            return false;
    }

    this.loadJosonData = function() {
        var mygetrequest = ajaxRequest();

        mygetrequest.onreadystatechange = function() {
            if (mygetrequest.readyState==4) {
                if (mygetrequest.status==200 || window.location.href.indexOf("http")==-1) {
                    var jsondata=eval("("+mygetrequest.responseText+")"); //retrieve result as an JavaScript object
                } else {
                    alert("An error has occured making the request");
                }
            }
        }

        mygetrequest.open("GET", 'some_url', true);
        mygetrequest.send(null);
    };
}

Now I want to use the jsondata value returned from the AJAX call, what is the best way to return the jsondata variable?

Jonathan Eustace
  • 2,469
  • 12
  • 31
  • 54
Rex
  • 251
  • 2
  • 4
  • 10
  • Invoke a callback once you have `jasondata` to continue processing the data/what you want to do after. Furthermore, `eval`? – Paul S. Aug 01 '13 at 23:17
  • @FelixKling I don't think this is actually a duplicate. This question is about how to implement data ferrying from the AJAX request to whatever is invoking the instance's `loadJSONData` method, and I don't believe your question/answer would adequately cover how to implement the callback pattern. – Asad Saeeduddin Aug 01 '13 at 23:21
  • 1
    @Asad: Mmmh, my answer (and the non-jQuery answer) is all about callbacks, but ok :) – Felix Kling Aug 01 '13 at 23:25
  • 1
    @Asad I'd say the callback pattern is *exactly* what that answer covers. What would you say the answer covers, if not callbacks in asynchrous operations? – apsillers Aug 01 '13 at 23:25

0 Answers0