window.history.pushState第二次无法工作

window.history.pushState not working for a second time

本文关键字:工作 第二次 history pushState window      更新时间:2023-09-26

我有一个页面,其中有一个过滤器列表,我想重新加载其主要内容。我正试图通过使用window.history.pushState (HTML5)来做到这一点,以保持每次用户更改过滤器时更新url的查询字符串。

这适用于第一个过滤器,当我在第一个过滤器之后添加另一个过滤器时不起作用。

这是我的代码。函数FilteredByHospital()在医院列表发生变化时调用。
var filters = new Object();
filters.Hospitals = new Array();
function FilteredByHospital(hospitalId) {
    debugger;
    var obj = { hospitalId: hospitalId };
    filters.Hospitals.push(obj);
    var isFirstFilter = window.location.href.indexOf('?') == -1;
    var currentUrl = window.location.href;
    if (isFirstFilter) {
        window.history.pushState(filters, "Filter_" + hospitalId, currentUrl + "?hospitalIds[0]=" + hospitalId);
    } else {
        window.history.pushState((filters, "Filter_" + hospitalId, currentUrl + "&hospitalIds[" + (filters.Hospitals.length - 1) + "]=" + hospitalId));
    }
}

医院清单(Razor)

<div class="FilterBox">
    @foreach (var hospital in Model.Hospitals)
    {
        <input style="cursor: pointer;" type="checkbox" name="HospitalId" value="@(hospital.Value)" onchange="FilteredByHospital('@(hospital.Value)')"/><span>@(hospital.Text)</span><br/>
    }
</div>

当我选择其中一个医院复选框时,URL正确地更改为http://localhost:56195/ApplicationHealthCheck/Index?hospitalIds[0]=139961407289011,并且我的控制器的操作被击中。

当我对另一个复选框再次执行此操作时,URL保持不变,并且只使用第一个医院ID再次命中该操作。URL应该改为http://localhost:56195/ApplicationHealthCheck/Index?hospitalIds[0]=139961407289011&hospitalIds[1]=26419769705609

我做错了什么?

在第二个pushState调用中有一对额外的括号。

取代
window.history.pushState((filters, "Filter_" + hospitalId, currentUrl + "&hospitalIds[" + (filters.Hospitals.length - 1) + "]=" + hospitalId));

window.history.pushState(filters, "Filter_" + hospitalId, currentUrl + "&hospitalIds[" + (filters.Hospitals.length - 1) + "]=" + hospitalId);

仔细看一下这一行代码:

window.history.pushState((filters, "Filter_" + hospitalId, currentUrl + "&hospitalIds[" + (filters.Hospitals.length - 1) + "]=" + hospitalId));

您注意到pushState((的双括号了吗?

在这一行中,您是而不是用三个参数调用pushState。将逗号操作符应用于参数,然后将结果传递给pushState。你的代码被求值为

window.history.pushState(currentUrl + "&hospitalIds[" + (filters.Hospitals.length - 1) + "]=" + hospitalId);

这显然是不对的