关于jquery:更改url而不使用javascript重定向

change url without redirecting using javascript

本问题已经有最佳答案,请猛点这里访问。

我想知道如何在不重定向的情况下更改URL,就像在这个网站上一样:http://dekho.com.pk/ads-in-lahore当我们点击标签时,URL会改变,但是页面会完全重新加载。StackOverflow还有其他问题表明这是不可能的,但我想知道上面提到的网站是如何实现的。谢谢


使用pushState

1
window.history.pushState("","", '/newpage');


如果您想确切了解它们使用的是什么,那么它是backbone.js(请参见第4574行和4981行)。这一切都与jquery源代码混淆了,但这些是带注释的Backbone.Router源代码文档页面的相关行:

支持检查:

1
2
  this._wantsPushState = !!this.options.pushState;
  this._hasPushState = !!(this.options.pushState && window.history && window.history.pushState);

route功能:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
route: function(route, name, callback) {
    Backbone.history || (Backbone.history = new History);

    if (!_.isRegExp(route)) route = this._routeToRegExp(route);

    if (!callback) callback = this[name];

    Backbone.history.route(route, _.bind(function(fragment) {
        var args = this._extractParameters(route, fragment);

        callback && callback.apply(this, args);

        this.trigger.apply(this, ['route:' + name].concat(args));

        Backbone.history.trigger('route', this, name, args);
    }, this));

    return this;
},

在哈希和推送状态之间进行选择:

1
2
3
4
5
6
7
8
9
// Depending on whether we're using pushState or hashes, and whether
// 'onhashchange' is supported, determine how we check the URL state.
if (this._hasPushState) {
    Backbone.$(window).bind('popstate', this.checkUrl);
} else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
    Backbone.$(window).bind('hashchange', this.checkUrl);
} else if (this._wantsHashChange) {
    this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
}?

更多关于他们的目的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// If we've started off with a route from a `pushState`-enabled browser,
// but we're currently in a browser that doesn't support it...
if (this._wantsHashChange && this._wantsPushState && !this._hasPushState && !atRoot) {
    this.fragment = this.getFragment(null, true);
    this.location.replace(this.root + this.location.search + '#' + this.fragment);

    // Return immediately as browser will do redirect to new url
    return true;

    // Or if we've started out with a hash-based route, but we're currently
    // in a browser where it could be `pushState`-based instead...
} else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
    this.fragment = this.getHash().replace(routeStripper, '');
    this.history.replaceState({}, document.title, this.root + this.fragment);
}

if (!this.options.silent) return this.loadUrl();

还有优雅的政变:

1
2
3
4
// If pushState is available, we use it to set the fragment as a real URL.
if (this._hasPushState) {
     this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
}

您应该阅读我在顶部提供的注释主干.js链接。信息非常丰富。