【问题标题】:jQuery AJAX - Redirect to 404 page when load method failsjQuery AJAX - 加载方法失败时重定向到 404 页面
【发布时间】:2017-07-21 12:48:40
【问题描述】:

我的网站使用 jQuery load 方法通过 AJAX 加载所有页面。我已尽力将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.status404statussuccess,我尝试在load 函数条件下执行我的代码,但没有运气。还是行不通。有人可以帮忙吗?

- 如何使用 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');
    }
});

【问题讨论】:

    标签: javascript php jquery ajax wordpress


    【解决方案1】:

    我终于解决了我的问题。

    在意识到响应返回了我想要的结果后,我猜测并认为问题在于返回的状态是 404,而实际上,我想要的是 200。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多