【问题标题】:How to make multiple calls for XMLHttpRequest如何多次调用 XMLHttpRequest
【发布时间】:2014-07-14 20:02:57
【问题描述】:

我是 javascript 新手,我正在尝试使用 XMLHttpRequest 发出异步 http 请求。为了说明,我有以下代码:

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

期望的行为是调用两个回调函数一次,但观察到的行为是第一个函数被调用一次并且页面停止。

我读到原因可能是 xhr 的重复使用,但是,如果我错了,请纠正我,初始化会强制变量在函数的范围内。

【问题讨论】:

    标签: javascript html ajax xmlhttprequest


    【解决方案1】:

    当您在文档加载后调用document.write 时,整个文档都会被覆盖,所以一切都消失了。

    在异步函数的回调中调用document.write肯定会在文档初始加载之后。

    改成类似

    var element = document.getElementById('result');
    
    element.innerHTML += 'first callback <br/>';
    

    并确保在 DOM 中有一个具有该 ID 的元素

    FIDDLE

    【讨论】:

      猜你喜欢
      • 2012-12-27
      • 1970-01-01
      • 1970-01-01
      • 2018-03-12
      • 2020-12-03
      • 1970-01-01
      • 2015-09-29
      • 2013-03-18
      • 2010-11-05
      相关资源
      最近更新 更多