javascript 从 responseText 中获取特定内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13460745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get specific content off responseText
提问by nikolas
I am making an ajax call and I get the content from responseText
.
我正在进行 ajax 调用,我从responseText
.
I confirm by using alert
that inside, the responseText
contains the entire page as a string
.
我通过alert
在里面使用来确认,responseText
包含整个页面作为string
.
That's fine. Now I need to extract specific contents from the string by converting it to DOM and using getElementsByTagName
, getElementsByName
etc...
没关系。现在,我需要将其转换为DOM并使用提取从字符串具体内容getElementsByTagName
,getElementsByName
等...
My problem is that none of these seems to work.
我的问题是这些似乎都不起作用。
I've read many references on using responseXML
instead of responseText
but this gives me back null
.
我已经阅读了许多关于使用responseXML
而不是的参考资料,responseText
但这让我回到了null
.
So, by sticking to responseText
, how can i get the specific elements that I want?
那么,通过坚持responseText
,我怎样才能获得我想要的特定元素?
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>
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
如何访问表的第二行及其值?或者 div 等等。所以,现在在我的实际 html 中,我有这样的东西
<html>
<head>.....</head>
<body>
<table><tr><td id="test">Test</td></tr></table>
</body>
</html>
i want the extracted element/value to be parsed inside the table of my actual html..
我希望在我的实际 html 的表格中解析提取的元素/值。
document.getElementById('test').innerHTML = the_extracted_elements_from_responseText
document.getElementById('test').innerHTML = the_extracted_elements_from_responseText
回答by Asad Saeeduddin
You need to use a DOMParser
on the html and use DOM traversal methods on the resulting document to return the desired node(s).
您需要DOMParser
在 html 上使用 a并在结果文档上使用 DOM 遍历方法以返回所需的节点。
var parser=new DOMParser();
var xmlDoc=parser.parseFromString(responseText,"text/xml");
var tds = xmlDoc.getElementsByTagName("td");
Note that IE would require new ActiveXObject("Microsoft.XMLDOM");
instead.
请注意,IE 将需要new ActiveXObject("Microsoft.XMLDOM");
。