7

我可以将数据设置到 History.js 的 State.data 中,如下所示:

var pushStateData = {};

function RetrieveSearchResults(type, url, searchData) {//, showResetButton, 
controlToFocus, navDirection) {

    pushStateData = {
        SearchType : type,
        SearchData : searchData,
    };

    RetrievePageResults(true, url, pushStateData);
}

function RetrievePageResults(pushNewUrl, url, pushStateData) {
    navigationInProgress = true;
    if (pushNewUrl) {
        if (window.History) {
                window.History.pushState(pushStateData, null, url);                                            
        }

        $.get(url, pushStateData.SearchData, function (reply) {
            $("#search-results").html(reply);
            navigationInProgress = false;            
        });
    }

如果我在 window.History.pushState 语句上设置断点,在 Chrome 中,我可以清楚地看到 pushStateData 具有所需的值。

但是,当我尝试检索数据时:

$(window).bind("statechange", function (e) {
        if (!navigationInProgress) { 
            var State = window.History.getState();

            if (window.console && window.console.log) {
                console.log("popstate", State, window.location.href);
            }

            RetrievePageResults(false, State.cleanUrl, State.data);
        }
    });

当我在 RetrievePageResults 语句上设置断点时,State.data 对象不再具有我设置的任何值。State.data 已定义,并且不为空,但它是一个没有任何明显值的空对象。

谢谢,斯科特

4

1 回答 1

5

我看不出 State.data 有什么问题,当您发出 pushState 时,请确保调用 History.js 方法:

History.pushState({state:1}, "State 1", "?state=1");

在哪里:

  • 第一个参数 => 数据
  • 第二个参数 => 名称
  • 第三个参数 => 网址

似乎您没有通过状态,并且只有当且仅当您调用 History.pushState 时,数据才会出现。当您直接访问 URL (/?state=1) 时,状态中将没有数据,只有在通过 History.pushState 推送状态时向后/向前导航时数据才可用。

旁注:确保您的 navigationInProgress 变量是固定的,您不希望它停在那里。在监听错误回调时 $.get 请求失败时重置它。当您的 pushNewUrl 为 false 时,重置 navigationInProgress 属性。

于 2012-08-11T23:29:30.030 回答