// 优化后的banner.js
(function () {
// 设置innerHTML
function setInnerHTML(el, html) {
if (el) el.innerHTML = html;
}
// AJAX GET请求
function ajaxGet(url, callback, errorCallback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
try {
var res = JSON.parse(xhr.responseText);
callback(res);
} catch (e) {
console.error('JSON解析失败', e);
if (errorCallback) errorCallback(e);
}
} else {
console.error('请求失败', xhr.status);
if (errorCallback) errorCallback(xhr.status);
}
}
};
xhr.send();
}
// 渲染banner
function renderBanner(bannerList) {
var bannerHtml = '';
bannerList.forEach(function (banner) {
bannerHtml += '
' +
'
' +
'
' +
'

' +
'
' +
'
' +
'
' + (banner.title || '') + '' +
'
' + (banner.desc || '') + '' +
'
' +
'查看详情' +
'' +
'
' +
'
' +
'
';
});
var carouselItem = document.querySelector('#test10 div[carousel-item]');
setInnerHTML(carouselItem, bannerHtml);
}
// 主流程
ajaxGet('/index/index/bannerlist', function (res) {
// console.log('banner接口返回:', res);
if (res && res.code === 1 && Array.isArray(res.banner)) {
renderBanner(res.banner);
// 确保layui和carousel已加载
if (window.layui) {
layui.use(['carousel'], function () {
var carousel = layui.carousel;
carousel.render({
elem: '#test10',
width: '100%',
height: '100vh',
interval: 4000,
anim: 'fade',
autoplay: true,
full: false,
arrow: 'hover'
});
});
} else {
console.error('layui未加载');
}
} else {
console.error('banner数据异常', res);
}
}, function (err) {
console.error('banner数据请求失败', err);
});
})();