我通过 AJAX 请求获得了一个 html 页面
$.ajax({
async: true,
method: 'GET',
url: linkPage,
// cache: true,
success: function (data) {
console.log(data);
}
});
我得到的数据格式是这样的:
<!DOCTYPE html>
<html>
<head>
...
</head>
<body id="sustainable" class='sustainable'>
<div id="wrap">
<main class="temp>
<section class="sec01">
...
</section>
</main>
</div>
</body>
</html>
现在我想获取 body id 和 class(即“可持续的”)通过此代码:
$(data).find('body').attr('class');
但我不知道为什么我不能得到它,它返回了不明确的。但是当我得到 html 内容或类时<main>
通过这段代码:
$(data).find('main').attr('class');
$(data).find('main').html();
它返回的正是我想要的。有人能解释一下为什么吗?
到目前为止,我已经通过创建这样的虚拟 DOM 尝试了一些解决方案,我可以选择<body>
and <main>
来自我想要的 AJAX 数据:无法从ajax响应获取body元素 https://stackoverflow.com/questions/7001926/cannot-get-body-element-from-ajax-response
但我还是想知道为什么我不能选择<body>
class 和 html 作为第一种情况?
看起来,当给定一个这样的字符串时,jQuery 将只保存身体的内容物进入其收藏:
const data = `<!DOCTYPE html>
<html>
<head>
...
</head>
<body id="sustainable" class='sustainable'>
<div id="wrap">
<main class="temp>
<section class="sec01">
...
</section>
</main>
</div>
</body>
</html>`;
console.log($(data)[0]);
console.log($(data)[1]);
console.log($(data)[2]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
(检查您的浏览器控制台。它正在选择周围的文本节点#wrap
, and #wrap
本身,但是not the <head>
or <body>
)
您可以使用 DOMParser 来代替,它将尝试将整个字符串放入文档中,而不试图遗漏某些内容:
const data = `<!DOCTYPE html>
<html>
<head>
...
</head>
<body id="sustainable" class='sustainable'>
<div id="wrap">
<main class="temp>
<section class="sec01">
...
</section>
</main>
</div>
</body>
</html>`;
const doc = new DOMParser().parseFromString(data, 'text/html');
console.log(doc.body.className);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
使用 DOMParser 的另一个好处是,与 jQuery 不同,它不会在 HTML 字符串中执行可能不安全的代码:
const data = `<!DOCTYPE html>
<html>
<head>
...
</head>
<body id="sustainable" class='sustainable'>
<img src onerror="alert('evil')">
</body>
</html>`;
$(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
jQuery version, unsafe
const data = `<!DOCTYPE html>
<html>
<head>
...
</head>
<body id="sustainable" class='sustainable'>
<img src onerror="alert('evil')">
</body>
</html>`;
const doc = new DOMParser().parseFromString(data, 'text/html');
console.log(doc.body.className);
DOMParser version, safe
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)