简体   繁体   中英

How to make multiple calls for XMLHttpRequest

I'm new to javascript and I'm trying to make an asynchronous http request using XMLHttpRequest. For illustration, I have the following code:

        function launchRequest(request, callback) {
            var xhr = new XMLHttpRequest();

            xhr.open("POST", "/api", true);
            xhr.onload = function(e) {
                callback(xhr.responseText);
            }   
            xhr.send(JSON.stringify(request));
        }

        function getAlbums(callback) {
            launchRequest({
                "command" : "getfolders"
            }, callback);
        }

        function getPhotosFromAlbum(albumId, callback) {
            launchRequest({
                "command" : "getphotos",
                "arguments" : {
                    "foldername" : albumId
                }
            }, callback);
        }

        getAlbums(function(result) {
            document.write('first callback <br/>');
        });


        getAlbums(function(result) {
            document.write('second callback <br/>');
        });

The desired behaviour is to call both the callback functions once, but the observed behaviour is that the first function is called once and the page stalls.

I've read that the cause could be the repeated usage of xhr but, correct me if I'm wrong, the initialization forces the variable to be in the function's scope.

When you call document.write after the document has loaded, the entire document is overwritten, so everything is gone.

Calling document.write in the callback of an async function will certainly be after the document has initially loaded.

Change it to something like

var element = document.getElementById('result');

element.innerHTML += 'first callback <br/>';

and make sure you have an element with that ID in the DOM

FIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM