我想知道使用 fetch api ( Is there a way to not send cookies when making an XMLHttpRequest on the same origin? ) 从 responseText 中获取用户可见的标题、关键字和内容的最佳方法是什么
目前,我使用正则表达式从响应文本中获取标题,例如:
var re_title = new RegExp("<title>[\n\r\s]*(.*)[\n\r\s]*</title>", "gmi");
var title = re_title.exec(responseText);
if (title)
title = title[1]
要获取关键字元标记中的内容,我需要使用几个正则表达式。
为了让内容对用户可见,我们不需要 script、div 等标签,也不需要 script 标签之间的文本。这是为了仅获取响应正文中有意义的词。
我认为(也根据各种 stackoverflow 帖子)为此使用正则表达式并不是正确的方法。有什么替代方案?
最佳答案
作为zzzzBov前面提到,您可以使用浏览器的 DOMParser
API 实现,通过解析 fetch
请求的 response.text()
来实现此目的。下面是一个为自己发送此类请求并解析标题、关键字和正文文本的示例:
<!DOCTYPE html>
<html>
<head>
<title>This is the page title</title>
<meta charset="UTF-8">
<meta name="description" content="Free Web Help">
<meta name="keywords" content="HTML,CSS,XML,JavaScript">
<meta charset="utf-8">
<script>
fetch("https://dl.dropboxusercontent.com/u/76726218/so.html")
.then(function(response) {
return (response.text());
})
.then(function(responseText) {
var parsedResponse = (new window.DOMParser()).parseFromString(responseText, "text/html");
document.getElementById("title").innerHTML = "Title: " + parsedResponse.title;
document.getElementById("keywords").innerHTML = "Keywords: " + parsedResponse.getElementsByName("keywords")[0].getAttribute("content");
document.getElementById("visibleText").innerHTML = "Visible Text: " + parsedResponse.getElementsByTagName("body")[0].textContent;
});
</script>
</head>
<body>
<div>This text is visible to the user.</div>
<div>So <i>is</i> <b>this</b>.</div>
<hr>
<b>Results:</b>
<ul id="results">
<li id="title"></li>
<li id="keywords"></li>
<li id="visibleText"></li>
</ul>
</body>
</html>
我在 Fetch API 上找到了 Mozilla 的文档, Using Fetch , 和 Fetch basic concepts有帮助。
关于javascript - 从 http 响应中获取 API : Get title, 关键字和正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32210341/