Javascript executes procedures incorrectly

I am trying to use JavaScript to control the contents of a page on a dummy web page that I create.

To this end, I wrote a small function called writeText(file_name, location), which receives the HTML file indicated by the file name and prints the contents of this file in innerHTMLpairs of tags <div>, the id attribute corresponds to the field location.

Then I wrapped the calls in other functions to automate the complete creation of such pages.

So, I call something like this:

function displayHome() {
    writeText('homeMain.html', 'mainFrame');
    writeText('homeSide.html', 'sideFrame');
}

... to display the home page.

However, when I call this function, the display updates only the object 'sideFrame'and does not make any changes to the contents 'mainFrame'. But if I interrupt the warning function ("Dummy") between two calls writeText(), then both contentFrames files are updated correctly.

I was wondering if anyone had seen this before, and if anyone knows how to fix it.

For completeness (this was copied almost verbatim on the w3schools website):

function writeText(script_file, location) {
    if (window.XMLHttpRequest)  {
        xmlhttp = new XMLHttpRequest();
    }   else    {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
        document.getElementById(location).innerHTML = xmlhttp.responseText;
    }
xmlhttp.open("GET",script_file,true);
xmlhttp.send();
}
+3
source share
1 answer

You use the xmlhttp global variable so that it gets clobbered the second time the function works. The request itself is asynchronous, so the second call is made while the first one is still running.

, ( xmlhttp), "var" xmlhttp:

var xmlhttp;
if (window.XMLHttpRequest)  {
    xmlhttp = new XMLHttpRequest();
}   else    {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
+8

All Articles