0

I am trying to load a web page through Javascript code and parse it to get the value of certain element using XPath. The code I have written to create a document object reurns {location: null} for every URL. The code is given below:

var req = new XMLHttpRequest();  
        req.open('GET', 'https://www.someurl.com', false);  
    req.overrideMimeType('text/xml; charset=windows-1251'); // for Cyrillic     
        req.send(null);
        if(req.status == 200) { 
           //console.log(req.responseText);
           var xmlString = req.responseText;
           var parser = new DOMParser();
           var xmlDoc = parser.parseFromString(xmlString, "text/xml"); 
            console.log(JSON.stringify(xmlDoc)); // it outputs {"location": null}

        }

Please let me know if I am mistaking something.

user
  • 568
  • 5
  • 19

1 Answers1

0

This is due to the asynchronous behaviour of XMLHttpRequest(). You are getting null because req.send(null) is an asynchronous call and the response will be handled separately by an event handler.

For more information on asynchronous behaviour, please refer to Asynchronous Javascript

Basically, you need to attach an event handler to handle the response of XMLHttpRequest.

req.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      // do your thing here
    }
};

This is done before your req.send(null);

Matthew
  • 16
  • 2