weixin_33726318 2011-07-20 21:36 采纳率: 0%
浏览 34

进行并行ajax请求

i have javascript code that does these things in a loop

  1. create a div element,append it to the dom and get its reference
  2. pass this reference to a function that makes an ajax post request
  3. set the response of the ajax request to the innerHTML of the passed element reference

here is the code

window.onload = function () {
    var categories = document.getElementById('categories').children;
    for (i = 0; i < categories.length; i++) {
        var link = categories[i].children[1].children[0].attributes['href'].nodeValue;
        var div = document.createElement('div');
        div.className = "books";
        div.style.display = "none";
        categories[i].appendChild(div);
        getLinks(link, div);
    }
}

function getLinks(url, div) {
    xhr = new XMLHttpRequest();
    xhr.open('POST', 'ebook_catg.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    url = encodeURIComponent(url)
    var post = "url=" + url;
    xhr.node=div;                         //in response to Marc B's suggestion
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            xhr.node.innerHTML = xhr.responseText;
            xhr.node.style.display = "block";
        }
    }
    xhr.send(post);
}

now when i check this in firebug i can see that the div element is created and appended to the categories element and its display is set to hidden. also the ajax post requests are being sent and the response is being received as expected. But the innerHTML property of div is not set and neither its display is set to block. This means that the function getLinks loses the div reference.

when i type console.log(div) in the firefox console it says ReferenceError: div is not defined.

can somebody explain whats going on here?


in response to Franks's comment i changed readystate to readyState and i am able to attach the response of the last ajax request to the dom. so that makes it obvious that the div reference is being lost.

  • 写回答

4条回答 默认 最新

  • weixin_33705053 2011-07-20 21:40
    关注

    Thats because you are using a public (global) variable div that keeps getting overwritten.

    Try this in your for loop:

    for (i = 0; i < categories.length; i++) {
        var link = categories[i].children[1].children[0].attributes['href'].nodeValue;
        var div = document.createElement('div'); //USE var!
        div.className = "books";
        div.style.display = "none";
        categories[i].appendChild(div);
        getLinks(link, div);
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记