修改查询字符串,不需要新的HTTP请求

Modify Query String Without new HTTP Request

本文关键字:HTTP 请求 不需要 查询 字符串 修改      更新时间:2023-09-26

是否有可能在不实际提交新的HTTP请求的情况下操作查询字符串?

例如,我有一个页面,允许用户对一些配置选项进行一系列更改。当他们第一次进入页面时,它将是以下URL:

www.mysite.com/options

当他们点击页面上的某些元素时,这里的链接或那里的单选按钮,URL将更改为:

www.mysite.com/options?xkj340834jadf

这样,用户可以复制URL,然后进入同一页面,并使配置与之前完全相同,但我不想在他们点击选项时提交新的请求。

这是可能使用javascript/jquery吗?

我认为这是不可能的。

最好的解决方案是在URL的末尾添加一个锚标记,然后jquery可以读取它来确定HTTP重定向。

我相信当你使用#!用于此目的时,google也会索引。

Facebook和Twitter新url中的shebang/hashbang(#!)是为了什么?

最好的解决方案是使用散列。正如Curt所说,#!是你告诉谷歌这是一个网络应用,但如果你不需要抓取,不用担心。

你可以这样使用:

var hash = location.hash; //or window.location.hash
hash = hash.replace(/^.*#!/, ''); // strip #! from the values
//do something with the values you got stored in `hash` var

如果你需要其他事情发生,比如每次哈希值改变时,你做一些事情,你可以绑定'hashchange'事件。例如:

我使用Ben Alman的jQuery hashchange event:

$(window).hashchange( function(){
    var hash = location.hash;
    hash = hash.replace(/^.*#!/, '');
    // do something with 'hash' everytime it changes
    // EXAMPLE:Set the page title based on the hash.
    document.title = 'The hash is '+hash+'.';
    return false; //this prevent browser from following the # after doing what you wanted
});