javascript - jQuery AJAX - 当加载方法失败时重定向到 404 页面

标签 javascript php jquery ajax wordpress

我的网站通过 AJAX 加载所有页面,使用 jQuery load 方法。我尽力去适应this tutorial到 WordPress。

我今天的问题是,load 方法返回错误时(例如由于链接损坏而导致的 404),AJAX 转换无法完成,并且页面根本没有改变

- 当加载方法失败时如何执行某些操作?

编辑:我在文档中找到了解决方案。

section.load(url + ' .cd-main-content > *', function (response, status, xhr) {
    //the code
}

现在它并没有像我想象的那样帮助我。因为,response 按预期返回 404 页面内容,status 返回错误和 xhr [object OBJECT]。我不明白的是为什么 response html 没有加载到 div 中...

- 我怎么知道这是 404 错误?

使用以下命令成功检查 404 错误:

if (status == "error" && xhr.status == "404") {
    console.log('this is a 404 error');
}

如果xhr.status404或者如果status,我尝试在load函数中执行我的代码code> 是成功,但没有运气。还是行不通。有人可以帮忙吗?

- 如何使用 jQuery 重定向到 WordPress 的 404.php 页面?

- 我应该如何处理其他错误代码?

抱歉,有很多问题......我不知道从哪里开始

这是 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 = $('<div class="cd-main-content ' + newSection + '"></div>');
        // 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("<body", "<container").replace("body>", "container>");
                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 <main> 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');
    }
});

最佳答案

我的问题终于解决了。

在意识到响应返回了我想要的内容后,我进行了猜测并假设问题在于返回的状态是 404,而实际上,200 正是我想要的。

所以我在 404.php 文件的开头添加了 status_header(200); ,现在它工作得很好。

我希望放弃 404 状态代码不会有问题,但这是我目前唯一的解决方案。

关于javascript - jQuery AJAX - 当加载方法失败时重定向到 404 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45238132/

相关文章:

php jquery json 即时搜索

javascript - jquery 从另一个复选框控制一个复选框

javascript - 在 chartist.js 中为 SVG 数据点添加轮廓

javascript - 从 foreach 创建动态 JSON

javascript - 正则表达式在/和/之间获取 URL 中的最后一个词

javascript - 为什么 document.createElement ('canvas' ).getContext ('2d' )。 hasOwnProperty ('font' )返回 false?

php - Laravel 软删除唯一列名

javascript - 使用 Javascript : How to create a 'Go Back' link that takes the user to a link if there's no history for the tab or window?

php - INSERTing 到表中时,我可以获取自动递增的主索引的值吗?

php - 直接从数组输出到 CSV 而不保存到 CSV 文件