AJAX function request stops previous load when called again - no jQuery please

徘徊边缘 提交于 2020-01-07 04:11:11

问题


I got this function to load an url into an element. The problem is that if I call it repetitively, like in a loop to load several elements, the current load stops:

function ajaxGetData(url, objId)
{
    var request;
    if (window.XMLHttpRequest) 
    { 
        request = new XMLHttpRequest();
    } 
    else if (window.ActiveXObject) 
    { 
        try 
        {
            request = new ActiveXObject('Msxml2.XMLHTTP');
        } 
        catch (e) 
        {
        try {
            request = new ActiveXObject('Microsoft.XMLHTTP');
        } 
        catch (e) {}
        }
    }

    if (!document.getElementById(objId))
    {
        return false;
    }
    var obj = document.getElementById(objId); /* <= fix: added var */
    ajaxLoadingIndicator(obj);

    request.addEventListener("progress", function(event){ajaxCallBack(event, obj)}, false);
    request.addEventListener("load", function(event){ajaxCallBack(event, obj)}, false);
    request.addEventListener("error", function(event){ajaxCallBack(event, obj)}, false);
    request.addEventListener("abort", function(event){ajaxCallBack(event, obj)}, false);

    request.onreadystatechange = function() 
    {
        if(request.readyState === 4) 
        { 
            if(request.status === 200) 
            { 
                obj.innerHTML  = request.responseText;
            }
            else
            {
                obj.innerHTML = '<div id="'+id+'">Error loading data.</div>';
            }
        }
    };
    request.open('GET', url, true);
    request.send(null);
}

function ajaxLoadingIndicator(obj)
{
    idBase = obj.id.split("_");
    id = idBase[0]+"_ajax_loading";
    obj.innerHTML = '<div id="'+id+'">Loading</div>';
}

function ajaxCallBack(e) 
{
    // Handle each event
    switch(e.type)
    {
        case 'error':
        {
            idBase = obj.id.split("_");
            id = idBase[0]+"_ajax_error";
            obj.innerHTML = '<div id="'+id+'">Server unavailable. Error loading data.</div>';
        } break;
    }
}

So if I do:

ajaxGetData(url1, objId1);
ajaxGetData(url2, objId2);
ajaxGetData(url3, objId3);

Only objId3 gets its content, the rest get stuck in the "loading" indicator.


回答1:


You've got a global variable obj in your code.

// function ajaxGetData(url, objId)
obj = document.getElementById(objId);
ajaxLoadingIndicator(obj);

All of your requests are sharing the same variable so that's why it appears that only the last request is completing. You can fix it using the var keyword in the declaration.



来源:https://stackoverflow.com/questions/41656342/ajax-function-request-stops-previous-load-when-called-again-no-jquery-please

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!