views:

77

answers:

2

Hey,

I'm doing some development using JS unde Adobe AIR. What I want to do is create a request to a remote website (for authentication for example).

The problem is not AIR related, it's a JS thing I can't get right. What I want to do is to retrieve the request body but if I just return the "str" var it shows "undefined". I've tried to declare it 'globally' inside the function but it didn't work. I'm guessing there is some scope issue that I'm overlooking.

        function doRequest(url){
            var req = new XMLHttpRequest();

            req.onreadystatechange = function(){
                if (req.readyState == 4) {
                    var str = req.responseText;
                    runtime.trace("deRequest result: " + str);

                        return str;
                }
            };
            req.open('GET', url, true);
            req.send(null);
        }
+1  A: 

You're returning it to the caller of onreadystatechange, which isn't likely to be interested. You can't return it at the end of doRequest either, because that will return immediately after calling req.send(null) and the value is not available yet (still to be obtained from the server). Some time later, your onreadystatechange handler gets called and you have the value. There's nowhere useful to return it to, at this point.

You need to structure your code so that instead of return str you do whatever it is you want to do with the return value - e.g. store it somewhere, display it using alert, pass it to another function.

Vinay Sajip
+2  A: 

You shouldn't be trying to capture the return value of the onreadystatechange function. XHR is asynchronous, which means this code is only fired whenever the request is done. So you have to prepared to do something with your response inside that function. The simplest thing to do is pass in a callback function.

    function doRequest(url, callback_func){
        var req = new XMLHttpRequest();

        req.onreadystatechange = function(){
            if (req.readyState == 4) {
                var str = req.responseText;
                runtime.trace("deRequest result: " + str);

                callback_func(str);
            }
        };
        req.open('GET', url, true);
        req.send(null);
    }

    function callback_func(data) {
        // do something with your response data
    }
Marco

related questions