Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

javascript - Get specific content off responseText

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...