1
<!DOCTYPE html>
 <html>
<head>
<script>
function loadXMLDoc()
{

if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

xmlhttp.onreadystatechange=function()
    {

    if (xmlhttp.readyState==4 && xmlhttp.status==200)
     {
      xmlDoc=xmlhttp.responseXML;


      }
    }
  xmlhttp.open("GET","cd_catalog.xml",true);
  xmlhttp.send();
}    
</script>
</head>
 <body>
  <script>
 loadXMLDoc();
    alert(xmlDoc)//dont work

     if(xmlDoc){console.log("true")}
     else(console.log("false"))

  </script>

  <div id="myDiv"></div>

 </body>
 </html>

If i try to access xmlDoc from within the body then the code does not work??Also i tried to know whether xmlDoc exist using if statement within the body like:

if(xmlDoc){console.log("true")}
else(console.log("false"))

but this also fails ,i m new to xmlDom so what mistake have i made above ?thanks

4

1 回答 1

1

xmlhttp.open("GET","xmlhttp_info.txt",false); sending asynchronously, the JavaScript does not have to wait for the server response, but can instead:

execute other scripts while waiting for server response & deal with the response when the response ready

So this is the reason why ur alert within the body doesn't work since js will continue to execute code. using async=false JavaScript will NOT continue to execute, until the server response is ready. If the server is busy or slow, the application will hang or stop.

Remember that async=false is not recommended, but for a few small requests this can be ok.

于 2013-06-12T11:02:17.270 回答