Javascript: window.location.search不更新?

Javascript: window.location.search does not update?

如果用户在搜索面板(页面)中输入这些参数,我需要更新 URL 中的搜索(查询)参数。我正在尝试这个:

$( document ).ready(function() {
    if ($('.o_website_license_search_panel').length) {
        $('.o_website_license_search_panel .o_search_submit').click(function () {
            var search = $.deparam(window.location.search.substring(1));
            console.log('before update')
            console.log(window.location.search)
            search.license_key = $(".o_website_license_search_panel input[name='license_key']").val();
            console.log('new obj ', search, $.param(search))
            window.location.search = $.param(search);
            console.log('after update')
            console.log(window.location.search)
        });
    }
});

我得到了这个输出:

before update
web.assets_frontend.js:1254 ?license_state=cancel
web.assets_frontend.js:1255 new obj  {license_state: "cancel", license_key: "test2"} license_state=cancel&license_key=test2
web.assets_frontend.js:1256 after update
web.assets_frontend.js:1257 ?license_state=cancel

如您所见,window.location.search 保持不变。有没有我想念的东西,或者它是这样设计的?..

设置 search(或 location 上除 hash 之外的任何其他属性)会导致重新加载页面。 属性 将继续保留其先前的值,直到发生这种情况,这就是您在日志记录语句中看到先前值的原因。 记录旧值后,除非您页面上的代码阻止它发生,否则页面将使用新的查询字符串重新加载,此时 location.search 会显示新字符串。

更多:window.location's properties on MDN

您也可以使用 javascript 提供的历史记录 api 来帮忙,但也让您知道它不会刷新页面,而是更改浏览器 url url 窗格,巧妙地完成你可以实现你想要的

访问这个link了解更多详情

https://developer.mozilla.org/en-US/docs/Web/API/History_API

备注

有时人们将此方法用于 ajax 目的,从而使他们能够存储历史数据以及添加书签