問題描述
我正在進行 ajax 調用,并從 responseText
獲取內容.
我通過使用 alert
確認,responseText
包含整個頁面作為 string
.
沒關系.現在我需要通過將字符串轉換為 DOM 并使用 getElementsByTagName
、getElementsByName
等從字符串中提取特定內容...
我的問題是這些似乎都不起作用.
我已經閱讀了很多關于使用 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 中獲取特定內容的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!