web-dev-qa-db-ja.com

JavaScriptを使用してリダイレクトせずにURLを変更する

このウェブサイトのようにリダイレクトせずにURLを変更する方法を知りたい http://dekho.com.pk/ads-in-lahore のときURLを変更するタブをクリックしますが、ページは完全にリロードされません。 stackoverflowにはそれが不可能であることを示す他の質問がありますが、上記のWebサイトがどのようにそれを実装しているか知りたいです。ありがとう

69
kb858

pushStateを使用:

window.history.pushState("", "", '/newpage');
155
Mihai Iorga

使用しているものを正確に知りたい場合は、Backbone.jsです(4574および4981行を参照)。すべてjQueryソースと混同されますが、これらは 注釈付きBackbone.Router source ドキュメントページの関連する行です。

サポートチェック

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

route関数:

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;
},

ハッシュおよびプッシュ状態 sの選択:

// 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);
}​

彼らがやっていることの詳細:

// 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();

そして coup 'd grace

// 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);
}

上部にある注釈付きのBackbone.jsリンクを読んでください。非常に有益です。

8
Jared Farrish