javascriptxmlhttprequestresponsetext

XmlHttpRequest.responseText result?


I am new to JavaScript. I need to test the output of XMLHttpRequest.responseText on a given URL. What is the simplest way to do it?

var url = "http://m.google.com/"; <br>
var xmlHttp = new XMLHttpRequest(); <br>
xmlHttp.open('GET', url, true); <br>
document.getElementById('main-content').innerHTML = xmlHttp.responseText; <br>

main-content is a <div> tag. The last line of code will replace the contents of the <div> tag with output of xmlHttp.responseText.

Now, when I open m.google.com in my regular browse and select "View Source", what part of the source gets placed within the <div> tag. Or let's stay I have to test this code in - where do I write this code?

Actually, I have an Android app that displays this HTML code result in a WebView.


Solution

  • Skip your frustrations and employ jQuery. It's an industry standard and almost every employer asks if you have experience with it.

    $.get({
     url:'url.html',
     data:{},
     success:function(evt){console.log(evt);}
    });
    

    However, if you want a go a more difficulte route:

    var url = "http://m.google.com/"; 
    var xmlhttp = new XMLHttpRequest(); 
    xmlhttp.open("GET", url,true);
    
     // subscribe to this event before you send your request.
     xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4) {
       //alert the user that a response now exists in the responseTest property.
       alert(xmlhttp.responseText);
       // And to view in firebug
       console.log('xhr',xmlhttp)
      }
     }
     xmlhttp.send(null)