問(wèn)題描述
我正在進(jìn)行 ajax 調(diào)用,并從 responseText
獲取內(nèi)容.
我通過(guò)使用 alert
確認(rèn),responseText
包含整個(gè)頁(yè)面作為 string
.
沒(méi)關(guān)系.現(xiàn)在我需要通過(guò)將字符串轉(zhuǎn)換為 DOM 并使用 getElementsByTagName
、getElementsByName
等從字符串中提取特定內(nèi)容...
我的問(wèn)題是這些似乎都不起作用.
我已經(jīng)閱讀了很多關(guān)于使用 responseXML
而不是 responseText
的參考資料,但這讓我返回了 null
.
那么,堅(jiān)持responseText
,我怎樣才能得到我想要的特定元素呢?
例如,如果我的回復(fù)包含以下內(nèi)容:
<html><head>....</head><身體>..........<桌子><tr><td>一些文本</td><td>其他文本</td></tr><tr><td>一些文本</td><td>其他文本</td></tr><tr><td>一些文本</td><td>其他文本</td></tr></表>somediv </div></身體></html>如何訪問(wèn)表格的第二行及其值?或 div 等.所以,現(xiàn)在在我的實(shí)際 html 中,我有這樣的東西
<html><頭>.....</頭><身體><table><tr><td id="test">Test</td></tr></table></身體></html>
我希望在我的實(shí)際 html 的表中解析提取的元素/值..
document.getElementById('test').innerHTML = the_extracted_elements_from_responseText
解決方案 您需要在 html 上使用 DOMParser
并在結(jié)果文檔上使用 DOM 遍歷方法以返回所需的節(jié)點(diǎn).
var parser=new DOMParser();var xmlDoc=parser.parseFromString(responseText,"text/xml");var tds = xmlDoc.getElementsByTagName("td");
請(qǐng)注意,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.
這篇關(guān)于從 responseText 中獲取特定內(nèi)容的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!