简体   繁体   English

获取xhr响应并进行解析

[英]Get xhr response and parse it

Hi I make an xmlHttpRequest like this: 嗨,我这样一个xmlHttpRequest:

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(). 我需要从响应中解析一些数据,而这只是一个网页,我需要通过诸如getElementById()之类的dom方法对其进行解析。 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 内容类型:text / xml

Otherwise responseXML is null 否则responseXML为null

So what are my options? 那我有什么选择呢?

PS: only js without any libraries. PS:只有js,没有任何库。 PPS: browser requirements: chrome, ff, ie8+ PPS:浏览器要求: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? 编辑:好的选项,哪个更好:1)将xhr.responsetext解析为字符串2)重定向到响应页面并对其进行解析。

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. 如果我理解您的问题,您只能以文本形式返回响应,但是您想将其作为HTML文档进行搜索,则可以尝试创建一个div并将html响应作为div的innerHTML。

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

Have you tried setting the responseType and/or using the overrideMimeType method? 您是否尝试设置responseType和/或使用overrideMimeType方法?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM