AJAX with history.pushState



我正在使用Firefox V26.0。JavaScript 将始终在所有链接上放置一个事件,以便在单击时进行 ajax 调用并异步加载页面。将加载的内容将是 JSON 字符串。它将解析字符串以包含所有信息(内容、page_title和 uri)。之后,我的脚本调用 window.history.pushstate() 来更改浏览器的历史记录。然后错误在源代码中。加载的 json 字符串将在 Firefox V26.0 的源代码中可见。这只有在我的 AJAX-success-function 中有 window.history.pushstate() 时才会出现。所以可以肯定的是,问题不在于

$('#ajax_load').html(obj.content);

因为如果此行将被注释掉,也会发生错误。仅当我使用 pushState() 时,加载的 JSON 才会在源代码中可见

我真的不知道为什么会出现这种情况。

这是完整的代码。我只将此脚本与jQuery结合使用,因此没有其他脚本会影响该问题

// In combination with jquery-1.9.1.min.js
$(document).ready(function(){
    $('body').addClass('js');
    $.ajaxLoad = function(href, popstate){
        popstate = typeof popstate !== 'undefined' ? popstate : true;
            $.ajax({
                type: 'GET',
                url: href,
                async: false,
                success: function(json){
                    var obj = JSON && JSON.parse(json) || $.parseJSON(json);
                    /**
                        obj will look like
                        {
                            content   : "content",
                            page_title: "Title of Page",
                            uri       : "/path/to/appliction/"
                        }
                    */
                    $('#ajax_load').html(obj.content);
                    if(popstate == true){
                        window.history.pushState({}, obj.page_title, obj.uri);
                    }
                    document.title = obj.page_title;
                    return false;
                },
                error: function(XMLHttpRequest, textStatus, errorThrown){
                    console.log(XMLHttpRequest);
                    return false;
                }
            }); 
    }
    $(document).on("click", 'a:not(".noAjaxLoad")', function(e){
        e.preventDefault();
        $.ajaxLoad($(this).attr("href"), true);
    });
});

如果你只尝试:

var obj = $.parseJSON(json);

听起来您正在使用pushState将 URI 设置为 JSON 数据的 URI。

您需要将其设置为要将原始页面转换为的页面的 URI(使用从 JSON 获取的数据)。

如果你还没有,那么你需要创建那个页面(可能是通过复制客户端JS对服务器端代码所做的工作)。

最新更新