Подтвердить что ты не робот

Изменить URL-адрес без перенаправления с помощью javascript

Я хотел бы знать, как изменить URL-адрес без перенаправления, как на этом сайте http://dekho.com.pk/ads-in-lahore когда мы нажимаем на вкладки, url изменяется, но дозагрузка страницы полностью перезагружается. Есть еще вопросы о stackoverflow, указывающие на то, что это невозможно, но я хотел бы знать, как это реализовал вышеупомянутый сайт. Благодаря

4b9b3361

Ответ 1

используйте pushState:

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

Ответ 2

Если вы хотите точно знать, что они используют, Backbone.js (см. строки 4574 и 4981). Все это смешалось там с источником jQuery, но это соответствующие строки аннотированная страница Backbone.Router источник:

поддерживает проверки:

  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, которую я предоставил в верхней части. Очень информативно.