AngularJS $ HTTP HTML解析器 [英] AngularJS $http HTML Parser
问题描述
所有的,我们正在开发与AngularJS web应用程序,我们有一个用例/需求(这不会发生很频繁的话),我们需要检索我们的静态服务器完整的HTML文档。然而,现在看来,$ HTTP对象返回一个原始的HTML字符串作为其数据。我们正试图避免使用外部库(像jQuery,例如),但我们需要在原始的HTML字符串解析成一个可查询的DOM对象。我们可以使用一个iframe,用它做,但我们也试图避免使用内部框架为众所周知的原因。
All, we're developing a webapp with AngularJS and we have a use case/requirement (that won't happen very often at all) where we will need to retrieve a complete HTML document from our static server. However, it appears that the $http object returns a raw HTML string as its 'data'. We are trying to avoid using an external library (like jQuery, for instance), but we need to parse that raw HTML string into a queriable DOM object. We could use an iframe and be done with it, but we're also trying to avoid using iframes for well-known reasons.
所以,问题是:AngularJS对HTML解析器(因为它为JSON)?否则,什么是处理这种情况的最优雅的方式?
So, the question is: does AngularJS have a parser for HTML (as it does for JSON)? Or else, what's the most graceful way to handle this case?
P.S:我们试图通过角的API文档筛选,但在所有诚实,他们被击中或错过与直观方便浏览。
P.S.: We tried sifting through Angular's API docs, but in all honesty they are hit-or-miss and unintuitive to navigate around.
推荐答案
如果您需要得到从字符串DOM元素编程,HTML解析成一个DOM对象pretty简单。
If you need to get a DOM element from the string programmatically, parsing html into a DOM object is pretty simple.
基本上你会用的DOMParser。
Basically you'd use DOMParser.
var parser = new DOMParser();
var doc = parser.parseFromString('<div>some html</div>', 'text/html');
doc.firstChild; //this is what you're after.
从那里,如果你想查询来获取与香草JS从中元素(意思是,你不想使用jQuery出于某种原因),你可以这样做:
From there if you wanted to query to get elements from it with vanilla JS (meaning, you don't want to use JQuery for some reason), you can do this:
//get all anchor tags with class "test" under a div.
var testAnchors = doc.firstChild.querySelectorAll('div a.test');
...但要注意: querySelectorAll
仅支持在IE8和更高
在包的方法:
DIV VAR =使用document.createElement('DIV');
div.innerHTML ='一些HTML';
VAR的结果= div.childNodes;
var div = document.createElement('div'); div.innerHTML = 'some html'; var result = div.childNodes;
......你注意,如果你把SVG或MATHML的,这种方法将返回HTMLUnknownElements。他们会看正常的,但他们将无法正常工作。
... do note that this method will return HTMLUnknownElements if you put SVG or MathML into it. They'll "look" normal, but they won't work.
这篇关于AngularJS $ HTTP HTML解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!