Get specific content off responseText

╄→尐↘猪︶ㄣ 提交于 2019-11-28 04:46:07

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/13460745/get-specific-content-off-responsetext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!