user2950593
user2950593

Reputation: 9627

Get xhr response and parse it

Hi I make an xmlHttpRequest like this:

var xhr = new XMLHttpRequest();

var params = 'gbook_text=' + encodeURIComponent('sdfsdf');

xhr.open("POST", '/gbook/save/7697256.html', true)
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4 && xhr.status == 200) {
    console.log(xhr.responseText);
  }
}


xhr.send(params);

And I need to parse some data from response which is just a webpage I need to parse It via dom methods like getElementById(). I know that I can write something like:

xhr.responseXML.getElementById('author')

But it works only if server sets a header

Content-Type: text/xml

Otherwise responseXML is null

So what are my options?

P.S: only js without any libraries. P.P.S: browser requirements: chrome, ff, ie8+

Edited: okay options, which one is better: 1)parse xhr.responsetext as a string 2)redirect to response page and parse it.How to do it, btw?

Upvotes: 2

Views: 2747

Answers (2)

idbehold
idbehold

Reputation: 17168

Have you tried setting the responseType and/or using the overrideMimeType method?

xhr.responseType = 'document';
xhr.overrideMimeType('text/xml');

Upvotes: 0

tik27
tik27

Reputation: 2698

If i understand your question, you can only get your response back in text, yet you want to search for it as an HTML document, you can try creating a div and putting the html response as the innerHTML of the div.

var res = document.createElement( 'div' );
res.innerHTML = xhr.responseText;
res.querySelector("#ElementID")

Upvotes: 2

Related Questions