假设我的网站上有两个资源列表:用户和组。当我以 10 为增量对每个页面进行分页时,我想保存列表的状态,这样当我将页面的 URL 提供给某人时,他们将被导航到具有相同页面大小的同一页面。
使用一个列表就很容易,我什至会放弃 Ajax 并使用简单的 HTTP 参数,但为了增加复杂性,Ajax 命令都采用相同的参数,例如:
user/getlist?maximum=10&offset=0&systemId=123456
group/getlist?maximum=10&offset=0&systemId=123456
最初,我考虑使用 anchor ,以便 URL 看起来像:
admin/users+groups.php#?maximum=10&offset=0&systemId=123456
但这显然不适用于两个列表。我可以在 jQuery 中轻松完成此操作,还是需要使用原始 JavaScript 进行编码?
最佳答案
您可以使用逗号(或破折号)分隔符来完成此操作,并使每个列表成为一个查询字符串参数。
更新,页面的 URL 如下所示:
admin/users+groups.php?ulist=10,0,123456&glist=12,0,123457
然后在javascript中,调用此函数来获取查询字符串参数值:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
// you should probably break this out and null check the parameter before splitting, but for the sake of brevity:
var userListVals=getParameterByName("ulist").split(",");
var groupListVals=getParameterByName("glist").split(",");
var userListURL = "/user/getlist?maximum=" + userListVals[0] + "&offset=" + userListVals[1] + "@systemId=" + userListVals[2];
var groupListURL = "/user/getlist?maximum=" + groupListVals[0] + "&offset=" + groupListVals[1] + "@systemId=" + groupListVals[2];
它依赖于正确顺序的值,但如果您自己生成 URL,那应该不是问题。
更新:
关于javascript - 如何添加/管理 Ajax 请求的持久 URL 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26659418/