Мой веб-сайт загружает все страницы через 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
JQuery AJAX – перенаправление на страницу 404 при сбое метода загрузки ⇐ Jquery
Программирование на jquery
1730230377
Anonymous
Мой веб-сайт загружает все страницы через AJAX с помощью метода загрузки jQuery. Я приложил все усилия, чтобы адаптировать это руководство к Wordpress.
Моя сегодняшняя проблема заключается в том, что когда метод load возвращает ошибку (например, 404 из-за неработающей ссылки), переход AJAX не завершается, и страница вообще не изменяется.
Как я могу выполнить что-то, если метод загрузки завершается неудачно?
[b]РЕДАКТИРОВАТЬ[/b]: я нашел решение в документации.
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');
}
});
Подробнее здесь: [url]https://stackoverflow.com/questions/45238132/jquery-ajax-redirect-to-404-page-when-load-method-fails[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия