【发布时间】:2017-10-09 10:54:48
【问题描述】:
我一直在尝试获取一个 HTML 文件并将其作为 jQuery 对象分配给一个变量。无济于事。我不确定 Stack Snippets 是否允许 GET 请求,所以这里也是 JSFiddle link。
var html = '<!DOCTYPE html><html lang="en"><head><title>Template</title></head><body itemscope itemtype="http://schema.org/WebPage"><main><header itemscope itemtype="http://schema.org/Country" itemprop="about"><h1 itemprop="name">Dummy heading</h1><p><span class="capital" title="Capital" itemprop="containsPlace"></span><span title="Dummy title" itemprop="additionalProperty" itemscope itemtype="http://schema.org/PropertyValue"><meta itemprop="name" content="Member of the EU since"><span itemprop="value" class="member-since">Dummy year</span></span></p></header><div itemprop="mainEntity" itemscope itemtype="http://schema.org/ItemList"><meta itemprop="description" content=""><article class="recipe loading" itemprop="itemListElement" itemscope itemtype="http://schema.org/Recipe"><meta itemprop="position" content=""><aside class="media"><div class="img-gallery" itemscope itemtype="http://schema.org/ImageGallery"></div><div itemscope itemtype="http://schema.org/VideoObject" class="youtube"><a itemprop="contentUrl" href="#" title=""><meta itemprop="name" content=""><meta itemprop="uploadDate" content=""><meta itemprop="description" content=""><img itemprop="thumbnailUrl" src="#" alt=""></a><div class="youtube-player"></div></div></aside><div class="text"><div class="wiki-text"><h1 itemprop="name">Dummy heading</h1><p itemprop="description"></p><p class="read-more">For more information about <span class="recipe-name"></span>, read the <a href="#" title="" itemprop="sameAs">Wiki</a>.</p></div><div class="rating" itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating">Rated <span itemprop="ratingValue">3.5</span>/5 based on <span itemprop="reviewCount">11</span> customer reviews</div><div class="cooking"><h2>Bake it yourself!</h2><div><meta itemprop="cookTime" content=""><span>Bake time: <span class="bake-time"></span></span></div><div class="ingredients-wrapper"><h3>Ingredients <small>for <span itemprop="recipeYield"></span></small></h3><div class="ingredients"><h4>Dummy heading</h4><ul></ul></div></div><div class="how-to"><h3>Steps</h3><ol></ol></div></div></div></article></div></main></body></html>';
$.ajax({
type: 'post',
url: "/echo/html/",
dataType: "html",
data: {
html: html,
delay: 1
}
}).done(function(data) {
// string
console.log(data);
// array
console.log($(data));
// array
console.log($.parseHTML(data));
// array
console.log($($.parseHTML(data)));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
HTML 有效。但是,我无法将其放入对象中。正如预期的那样,返回的数据是一个字符串。但是,当我尝试使用 $.parseHTML() 将该字符串解析为 HTML 或将其放入 jQuery 选择器 $() 甚至尝试两者时,我总是得到相同的结果:包含标题和主要元素的数组。
因此,在某种程度上,jQuery 仍然会解析它,并在头部元素和正文中的一个元素组成一个数组。但是为什么?我该如何解决这个问题,并将其转换为 jQuery 对象?我只对正文的内容感兴趣。
有a similar question,但接受的解决方案在进入 JSFiddle 时并没有帮助,而且我在本地使用 XAMPP 也遇到了这个问题。
【问题讨论】:
标签: jquery ajax html-parsing