开发者

Javascript asynchronous calls stepping on one another

I'm using AHAH (as outlined here http://microformats.org/wiki/rest/ahah) to make two calls to populate HTML on a page. The calls happen after the document is ready and are fired off one after another. The result, every time, is the first call gets overwritten with the last calls respon开发者_如何学运维se. So I'll have two of the same chunks of HTML on the page instead of two unique pieces of code. Sometimes the first call doesn't even get to evaluate it's call back and thus remains empty.

Any ideas?


If you're using the exact code on that page, it's not surprising, as the example there uses a single global variable to store the XMLHttpRequest being made. So there's no way it can work for more than one simultaneous request: calling the function a second time overwrites the req with a new one, causing the req read by ahahDone to be the wrong request.

If you want to allow this you'll have to make req a local variable (by declaring it var in function ahah()), and pass it with the target to the ahahDone() function. Or just do it inline:

function Element_loadHTML(element, url) {
    var req= null;
    if (window.XMLHttpRequest) {
        req= new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        try {
            req= new ActiveXObject('MSXML2.XMLHttpRequest');
        } catch() {}
    }
    if (!req) {
        element.innerHTML= 'Browser does not support XMLHttpRequest';
        return;
    }
    element.innerHTML= 'Loading...';

    req.onreadystatechange= function() {
        if (req.readyState===4)
            element.innerHTML= req.status===200? req.responseText : 'Error '+req.status;
    };
    req.open('GET', url);
    req.send(null);
} 

Element_loadHTML(document.getElementById('appdata'), 'appdata.part.html');
Element_loadHTML(document.getElementById('foo'), 'bar.part.html');

The stuff with the browser sniffing and trying to execute script tags is hopeless and broken; don't use it. It's not good practice to be loading <script> element content into the page.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜