从 responseText 中获取特定内容 [英] Get specific content off responseText

查看:15
本文介绍了从 responseText 中获取特定内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在进行 ajax 调用,并从 responseText 获取内容.

我通过使用 alert 确认,responseText 包含整个页面作为 string.

没关系.现在我需要通过将字符串转换为 DOM 并使用 getElementsByTagNamegetElementsByName 等从字符串中提取特定内容...

我的问题是这些似乎都不起作用.

我已经阅读了很多关于使用 responseXML 而不是 responseText 的参考资料,但这让我返回了 null.

那么,坚持responseText,我怎样才能得到我想要的特定元素呢?

例如,如果我的回复包含以下内容:

<html><head>....</head><身体>..........<桌子><tr><td>一些文本</td><td>其他文本</td></tr><tr><td>一些文本</td><td>其他文本</td></tr><tr><td>一些文本</td><td>其他文本</td></tr></表>

somediv </div></身体></html>

如何访问表格的第二行及其值?或 div 等.所以,现在在我的实际 html 中,我有这样的东西

<html><头>.....</头><身体><table><tr><td id="test">Test</td></tr></table></身体></html>

我希望在我的实际 html 的表中解析提取的元素/值..

document.getElementById('test').innerHTML = the_extracted_elements_from_responseText

解决方案

您需要在 html 上使用 DOMParser 并在结果文档上使用 DOM 遍历方法以返回所需的节点.

 var parser=new DOMParser();var xmlDoc=parser.parseFromString(responseText,"text/xml");var tds = xmlDoc.getElementsByTagName("td");

请注意,IE 将需要 new ActiveXObject("Microsoft.XMLDOM");.

I am making an ajax call and I get the content from responseText.

I confirm by using alert that inside, the responseText contains the entire page as a string.

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.

I've read many references on using responseXML instead of responseText but this gives me back null.

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>     

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>

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

解决方案

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");

Note that IE would require new ActiveXObject("Microsoft.XMLDOM"); instead.

这篇关于从 responseText 中获取特定内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆