JQuery AJAX – перенаправление на страницу 404 при сбое метода загрузкиJquery

Программирование на jquery
Ответить
Anonymous
 JQuery AJAX – перенаправление на страницу 404 при сбое метода загрузки

Сообщение Anonymous »

Мой веб-сайт загружает все страницы через AJAX с помощью метода загрузки jQuery. Я приложил все усилия, чтобы адаптировать это руководство к Wordpress.
Моя сегодняшняя проблема заключается в том, что когда метод load возвращает ошибку (например, 404 из-за неработающей ссылки), переход AJAX не завершается, и страница вообще не изменяется.
Как я могу выполнить что-то, если метод загрузки завершается неудачно?
РЕДАКТИРОВАТЬ: я нашел решение в документации.
section.load(url + ' .cd-main-content > *', function (response, status, xhr) {
//the code
}

Теперь это мне не помогает так, как я думал. Поскольку ответ возвращает содержимое страницы 404, как и ожидалось, статус возвращает ошибку и xhr [объект OBJECT]. Чего я не понимаю, так это почему HTML-код ответа не загружается в div...
Как я могу узнать, что это ошибка 404?
Успешно проверено на наличие ошибки 404 с помощью:
if (status == "error" && xhr.status == "404") {
console.log('this is a 404 error');
}

Я попробовал выполнить свой код в функции загрузки при условии, что xhr.status равен 404 или если статус успешен , безуспешно. Все еще не работает. Может ли кто-нибудь помочь?
Как я могу перенаправить на страницу WordPress 404.php с помощью jQuery?
Как мне обрабатывать другие коды ошибок?
Много вопросов, извините... Не знаю, с чего начать
Вот Javascript:
jQuery(document).ready(function (event) {

// select website's root url
var rootUrl = aws_data.rootUrl;
var isAnimating = false,
newLocation = '',
firstLoad = false;

// Internal Helper
$.expr[':'].internal = function(obj, index, meta, stack){
// Prepare
var
$this = $(obj),
urlinternal = $this.attr('href')||'',
isInternalLink;

// Check link
isInternalLink = urlinternal.substring(0,rootUrl.length) === rootUrl || urlinternal.indexOf(':') === -1;

// Ignore or Keep
return isInternalLink;
};

//trigger smooth transition from the actual page to the new one, excluding event on non relevant links
$('main').on('click', 'a[href]:internal:not(.no-ajaxy,.love-button,[href^="#"],[href*="#respond"],[href*="wp-login"],[href*="wp-admin"])', function (event) {
event.preventDefault();
//detect which page has been selected
var newPage = $(this).attr('href');
//if the page is not already being animated - trigger animation
if (!isAnimating) changePage(newPage, true);
firstLoad = true;
});
//detect the 'popstate' event - e.g. user clicking the back button
$(window).on('popstate', function (e) {
if (firstLoad) {
/*
Safari emits a popstate event on page load - check if firstLoad is true before animating
if it's false - the page has just been loaded
*/
var newPageArray = location.pathname.split('/'), //this is the url of the page to be loaded
//newPage = newPageArray[newPageArray.length - 1];
newPage = window.location.href;
if (!isAnimating && newLocation != newPage) changePage(newPage, false);
}
firstLoad = true;
});

function changePage(url, bool) {
isAnimating = true;
// trigger page animation
$('body').addClass('page-is-changing');
$('.cd-loading-bar').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function () {
loadNewContent(url, bool);
newLocation = url;
$('.cd-loading-bar').off('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend');
});
//if browser doesn't support CSS transitions
if (!transitionsSupported()) {
loadNewContent(url, bool);
newLocation = url;
}
}

function loadNewContent(url, bool) {
// I don't understand the line below
url = ('' === url) ? rootUrl : url;
var newSection = 'cd-' + url.replace(rootUrl, "");
var section = $('');
// this ajax request helps me applied Wordpress classes on the body element, which is not being reloaded below
$.ajax({url: url,
success: function(data){
data = data.replace("");
var classes = $(data).filter("container").attr("class");
$("body").attr("class", classes + " page-is-changing");
}
});

section.load(url + ' .cd-main-content > *', function (event) {
// load new content and replace content with the new one
$('main').html(section);
var delay = 1200;

//functions to execute after DOM is loaded
$(document).foundation();
makeFooterSticky();
window.scrollTo(0, 0);
$(".ajax-load-more-wrap").ajaxloadmore();
//ga('send', 'pageview', window.location.pathname);

setTimeout(function () {
//wait for the end of the transition on the loading bar before revealing the new content
$('body').removeClass('page-is-changing');
$('.cd-loading-bar').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function () {
isAnimating = false;
$('.cd-loading-bar').off('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend');
});
if (!transitionsSupported()) isAnimating = false;
}, delay);
if (url != window.location && bool) {
//add the new page to the window.history
//if the new page was triggered by a 'popstate' event, don't add it
window.history.pushState({
path: url
}, '', url);
}
});

}

function transitionsSupported() {
return $('html').hasClass('csstransitions');
}
});


Подробнее здесь: https://stackoverflow.com/questions/452 ... thod-fails
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Jquery»