我有一个代码块,我想对其进行现代化处理并使用fetch()api。 这是老同事的代码,请原谅缺乏细节。 本质上,我只是想转换此部分。 我的第一个障碍是获取请求对象的网址。
如何开始分解此代码块?
var HeaderSwitcher = {
currentHeader: 1,
loading: false,
load: function (direction) {
HeaderSwitcher.loading = true
$headerWidget.addClass('loading-widget')
let nextID = direction === 'next' ? HeaderSwitcher.currentHeader + 1 : HeaderSwitcher.currentHeader - 1
if (nextID > 7) {
nextID = 1
}
if (nextID < 1) {
nextID = 7
}
let nextHeader = ('0' + nextID).slice(-2)
$.ajax({
url: ajax_object.ajax_url + '?action=get_header_component&header=' + nextHeader,
success: function (data, status, xhr) {
console.log({data, status, xhr})
$('header').replaceWith(data)
$headerWidget.removeClass('loading-widget')
HeaderSwitcher.currentHeader = nextID
HeaderSwitcher.loading = false
// Check for any scripts corresponding to this header
var $script = $('script').filter(function (index, script) {
return script.src && script.src.indexOf('header-' + nextHeader) > -1;
});
if ($script.length) {
// Create new script
var script = document.createElement('script')
script.src = $script.attr('src')
// Remove and re-apply the script
$script.remove()
$('body').append(script)
} else {
// Create new script
var script = document.createElement('script')
script.src = ajax_object.theme_url + '/components/header/header-' + nextHeader + '/header-' + nextHeader + '.js';
$('body').append(script)
}
$('.header-widget .component-number').text(nextHeader)
window.renderButtons('header', nextHeader, $('.header-widget .component-header').get()[0])
$(window).trigger('load')
}
})
console.log(this)
}
} // HeaderSwitcher