我想知道使用 fetch api (有没有办法在同源发出 XMLHttpRequest 时不发送 cookie? https://stackoverflow.com/questions/9028234/is-there-a-way-to-not-send-cookies-when-making-an-xmlhttprequest-on-the-same-ori/30050285#30050285)
目前,我使用正则表达式从响应文本中获取标题,例如:
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 帖子)使用正则表达式并不是正确的方法。有什么替代方案吗?
As zzzzBov https://stackoverflow.com/users/497418/zzzzbov提到的,您可以使用浏览器的实现DOMParser
API 通过解析来实现这一点response.text()
of a fetch
要求。下面是一个为自身发送此类请求并解析标题、关键字和正文的示例:
<!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>
我找到了 Mozilla 的文档获取API https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API, 使用获取 https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch, and 获取基本概念 https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Basic_concepts有帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)