js通过接口来调用最新3篇文章
<script>
// 检查localStorage中是否有数据
const storedData = localStorage.getItem('articleListData');
if (storedData) {
// 如果有数据,则直接解析并使用,不发起请求
const data = JSON.parse(storedData);
displayArticles(data);
} else {
// 如果没有数据,则发起请求
fetch('https://apis.aaaa.com/sync/shopify/list?act=http&find=articles&limit=3')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
// 存储数据到localStorage
localStorage.setItem('articleListData', JSON.stringify(data));
displayArticles(data);
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
}
// 定义一个函数来显示文章
function displayArticles(data) {
const articleList = document.getElementById('articleList');
// 清空旧的内容(如果有的话)
articleList.innerHTML = '';
for (let i = 0; i < Math.min(3, data.data.length); i++) {
const article = data.data[i];
const blogId = article.blog_id;
const title = article.title;
const url = article.handle;
const bloghandle = article.blog_handle;
const imageSrc = article.image ? article.image.src : 'No Image';
const truncatedTitle = title.length > 30 ? title.substring(0, 40) + '...' : title;
const div = document.createElement('div');
div.innerHTML = `<a href="${bloghandle}/${url}" class="dfsgdfgre1232"><div class="uiosdg33"><img src="${imageSrc}" alt="${title}" /></div> <span>${truncatedTitle}</span> </a>`;
articleList.appendChild(div);
}
}
</script>
简化版:
<script>
fetch('https://apis.aaaa.com/sync/shopify/list?act=http&find=articles&limit=3')
.then(response => {
if (!response.ok) { throw new Error('Network response was not ok'); }
return response.json();
})
.then(data => {
const articleList = document.getElementById('articleList');
console.log(data);
for (let i = 0; i < Math.min(3, data.data.length); i++) {
const article = data.data[i];
const blogId = article.blog_id;
const title = article.title;
const url = article.handle;
const bloghandle = article.blog_handle;
const imageSrc = article.image ? article.image.src : 'No Image';
const truncatedTitle = title.length > 30 ? title.substring(0, 40) + '...' : title;
const div = document.createElement('div')
div.innerHTML = `<a href="${bloghandle}/${url}" class="dfsgdfgre1232"><div class="uiosdg33"><img src="${imageSrc}" alt="${title}" /></div> <span>${truncatedTitle}</span> </a>`;
articleList.appendChild(div);
}
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
</script>