问题描述
我正在进行ajax调用,我从 responseText
获取内容。
I am making an ajax call and I get the content from responseText
.
我通过 alert 在里面, responseText
将整个页面包含为字符串
。
I confirm by using alert
that inside, the responseText
contains the entire page as a string
.
没关系。现在我需要从字符串中提取特定内容,方法是将其转换为DOM并使用 getElementsByTagName
, getElementsByName
等...
That's fine. Now I need to extract specific contents from the string by converting it to DOM and using getElementsByTagName
, getElementsByName
etc...
我的问题是这些似乎都不起作用。
My problem is that none of these seems to work.
我读过许多关于使用 responseXML
而不是 responseText
但这会让我回来 null
。
I've read many references on using responseXML
instead of responseText
but this gives me back null
.
因此,通过坚持 responseText
,我如何获得我想要的特定元素?
So, by sticking to responseText
, how can i get the specific elements that I want?
例如,如果我的回复包含以下内容:
For instance if my response contains the following:
<html>
<head>....</head>
<body>....
.....
<table>
<tr>
<td>sometext</td>
<td>someothertext</td>
</tr>
<tr>
<td>sometext</td>
<td>someothertext</td>
</tr>
<tr>
<td>sometext</td>
<td>someothertext</td>
</tr>
</table>
<div> somediv </div>
</body>
</html>
如何访问表格的第二行及其值?或div等..
所以,现在在我的实际html中,我有这样的事情
how can I access the second row of the table and its value? Or the div etc..so, now in my actual html, i have sth like this
<html>
<head>.....</head>
<body>
<table><tr><td id="test">Test</td></tr></table>
</body>
</html>
我希望在我的实际html表中解析提取的元素/值..
i want the extracted element/value to be parsed inside the table of my actual html..
document.getElementById('test')。innerHTML = the_extracted_elements_from_responseText
document.getElementById('test').innerHTML = the_extracted_elements_from_responseText
推荐答案
您需要在html上使用 DOMParser
并在结果文档上使用DOM遍历方法来返回所需的节点。
You need to use a DOMParser
on the html and use DOM traversal methods on the resulting document to return the desired node(s).
var parser=new DOMParser();
var xmlDoc=parser.parseFromString(responseText,"text/xml");
var tds = xmlDoc.getElementsByTagName("td");
注意IE需要 new ActiveXObject(Microsoft.XMLDOM);
而不是。
这篇关于从responseText获取特定内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!