2025年06月14日/ 浏览 1
首先,我们定义一个函数fetchArticle
,它接受一个对象作为参数,该对象包含文章的所有必要信息(如标题、关键词、描述等),然后使用fetch
API进行网络请求。
“`javascript
function fetchArticle({ title, keywords, description }) {
// 构造请求的URL
const url = https://api.example.com/articles?title=${title}&keywords=${keywords}&description=${description}
;
// 使用fetch API发起请求
return fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(‘Network response was not ok’);
}
return response.json(); // 假设API返回的是JSON格式的数据
})
.then(data => {
// 假设API返回的数据中包含一个名为’content’的字段,里面是Markdown格式的文章内容
return data.content; // 返回Markdown格式的文章内容
})
.catch(error => {
console.error(‘Error fetching article:’, error);
throw error; // 抛出错误以便于调用者可以捕获并处理
});
}
“`
<pre>
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Article Viewer</title>
</head>
<body>
<h1>Article Preview</h1>
<pre id="article-content"></pre> <!-- 用于显示Markdown内容的预标签 -->
<script>
// 调用fetchArticle函数并处理结果
fetchArticle({ title: "My Awesome Article", keywords: "javascript, promise, ajax", description: "Learn about using promises in AJAX requests." })
.then(content => {
document.getElementById('article-content').textContent = content; // 更新页面上的内容为Markdown格式的文本
})
.catch(error => {
console.error('Failed to load article:', error); // 处理可能发生的错误
});
</script>
</body>
</html>
URLSearchParams
)来处理URL的构建。catch
来捕获和处理这些错误。