mko
mko

Reputation: 22044

Get stuck in the XMLHttpRequest

I made a simple html to play with XHR, but get no response from httpxml.responseText; But the script does work in the safari console.

<html><head></head><body>
        <div id="myDiv"></div>
        <button type="button" onclick="loadXMLDoc()">Change Content</button>
        <script type="text/javascript">
            function loadXMLDoc()
            {
            httpxml = new window.XMLHttpRequest;
            httpxml.open('GET','resources/xml/test.xml',true);
            httpxml.send();
            text = httpxml.responseText;
            alert(text);// there's no text in the alert window
            document.getElementById("myDiv").innerHTML=text;
            }
        </script>
    </body>
</html>

Upvotes: 0

Views: 1110

Answers (2)

Valky
Valky

Reputation: 1866

You should add the readyState test before.

function loadXMLDoc()
{
  httpxml = new window.XMLHttpRequest();
  httpxml.open('GET','yourpage.xml',true);
  httpxml.send(null);
  httpxml.onreadystatechange = function() {
  if(httpxml.readyState == 4) {
    text = httpxml.responseText;
    alert(text);
    document.getElementById("myDiv").innerHTML=text;
    }
  }
}

But for this, I will use jquery, so easier :

$('#mybutton').click(function(){ 
    $.GET('yourpage.xml',function(data){
      $('#mydiv').html(data); 
    }); 
});

Upvotes: 0

selbie
selbie

Reputation: 104514

Is it just me or are you passing "true" as the third parameter of httpxml.open? That means "perform the request asynchronously". Either change this parameter to "false" or set a readystate callback function that gets invoked when the network operation has completed.

Better example code here: http://www.w3.org/TR/XMLHttpRequest/

Upvotes: 2

Related Questions