change url without redirecting using javascript

I would like to know how to change the url without redirecting like on this website http://dekho.com.pk/ads-in-lahore when we click on tabs the url changes but the page dosent reload completely. There are other questions on stackoverflow indicating that it is not possible but i would like to know how the above mentioned website have implemented it. Thanks

127534 次浏览

use pushState:

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

如果您想确切地知道他们使用的是什么,那就是 Backbone.js(参见行 45744981)。这些都与 jQuery 源代码混在一起,但这些是 带注释的 Backbone.Router文档页面的相关行:

返回文章页面 支票:

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

The route function:

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

散列和推送状态之间做出选择:

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

And the 一击致命:

// 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 链接。