问题
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