使用JavaScript调用WordPress API获取随机文章
以下是通过JS调用WordPress API实现随机排列5篇文章的代码示例:
//定义WordPress API的请求URL
const apiUrl = 'https://your-wordpress-site/wp-json/wp/v2/posts?per_page=5&orderby=rand';
//使用fetch函数发起请求并处理响应数据
fetch(apiUrl)
.then(response => response.json())
.then(data => {
//遍历文章数据并显示在页面上
data.forEach(post => {
//创建文章元素
const postElement = document.createElement('div');
postElement.classList.add('post');
//添加文章标题和链接
const postTitle = document.createElement('h2');
postTitle.innerHTML = post.title.rendered;
const postLink = document.createElement('a');
postLink.href = post.link;
postLink.appendChild(postTitle);
postElement.appendChild(postLink);
//添加文章摘要
const postExcerpt = document.createElement('p');
postExcerpt.innerHTML = post.excerpt.rendered;
postElement.appendChild(postExcerpt);
//将文章元素添加到页面中
document.body.appendChild(postElement);
});
})
.catch(error => {
console.error('请求WordPress API时发生错误', error);
});
在上面的代码中,首先定义了WordPress API的请求URL,并使用fetch函数发起请求。请求的URL中包含了per_page=5和orderby=rand两个参数,分别表示每页返回5篇文章和按随机顺序排序。请求成功后,遍历响应数据中的每篇文章,并创建相应的文章元素,最后将它们添加到页面中显示出来。
需要注意的是,上面的示例代码中并没有对请求数据进行错误处理和异常捕获。在实际开发中,应该考虑到可能出现的网络错误、API响应异常等情况,并作出相应的处理。
原文地址: https://www.cveoy.top/t/topic/lF97 著作权归作者所有。请勿转载和采集!