在 URL 中的 AJAX 请求后捕获和更新变量值



我真的很感激这方面的帮助。我有一个页面,使用拉拉维尔分页显示商店中的产品。我在页面上有基于品牌、类别和可用产品的过滤器。为了过滤产品,我正在使用复选框。如果选中复选框,我使用 ajax 获取请求并通过 URL 将状态发送到控制器以过滤可用产品。

status =1 用于可用产品,status = 0用于所有产品。网址看起来像这样:

/Collections/Newest_Items?status=1&page=2

情况是这样的。我想知道是否可以更改 URL 中的变量值并根据页码和新过滤器动态重新生成 URL?这是一种使用 jquery 获取页面 URL 并更改值然后使用window.history.pushState("", "", URL);更改 URL 的方法吗? 这是我的 ajax:

$(document).on('click', "#only_available", function () {
if ($('#only_available').is(':checked')) {
var status = 1;
url = '/Collections/Newest_Items?status='+status;
} else {
var status = 0;
url = '/Collections/Newest_Items';
}
window.history.pushState("", "", url);
$.ajax({
url: '/Collections/Newest_Items',
type: "GET",
data: {status: status},
cash: false,
success:
function (response) {
$('#products-load').html(response);
}
});
});
});

我通过自己编写 URL 来做到这一点。在这种情况下,我必须在应用于页面的每个过滤器之后编写 URL。这样我就无法获取用户当前所在的页面,它会返回到第一页。但是我在这里想要实现的是,我想使 Url 动态地使用用户当前使用的页码,并应用所有过滤器。

您可以使用window.location.search

,它会给你类似的东西: 在你的例子中status=1&page=2。然后,您需要解析出这些变量以获取所需的页码。

好的,我想我明白你的要求。因此,对于您触发的每个唯一过滤器事件,您需要在pushstate之前查询当前 url,并使用如下所示的内容获取值。

例如,如果有人点击 Brand,那么你将获得新的brand变量以及当前statuspage变量,以便像这样使用 ajax 传递

也只是发布它而不是获取

$(document).on('click', ".brand", function () {
var brand = $(this).attr('id);
//Example how to use it: 
var params = parseQueryString();
var status = params["status"]);
var page = params["page"]);
// if you have more variables than this then you would add them here and make sure you pass them along to the ajax data.
url = '/Collections/Newest_Items?status='+status+'&page='+page+'&brand='+brand;
window.history.pushState("", "", url);
$.ajax({
url: '/Collections/Newest_Items',
type: "POST",
data: {status: status, page: page, brand: brand},
cash: false,
success:
function (response) {
$('#products-load').html(response);
}
});
});
var parseQueryString = function() {
var str = window.location.search;
var objURL = {};
str.replace(
new RegExp( "([^?=&]+)(=([^&]*))?", "g" ),
function( $0, $1, $2, $3 ){
objURL[ $1 ] = $3;
}
);
return objURL;
};

tnx 到 @CesarBielich 和 @Sokies 我终于设法解决了这个问题。 他们给了我部分答案,但不是全部。我使它对我的问题独一无二:

我们需要的是嵌套在 URL 中的路径和参数。 因此,要获取路由的路径,我们必须使用window.location.pathname,并且要获取所有参数,必须使用window.location.search。 之后,我们必须组合路径和参数,以便 URL 从中出来。 然后我们必须在此之后添加新参数,例如状态。以便控制器可以访问所有参数。旧参数和新参数。通过这种方式,Laravel分页知道要制作什么URL,在href链接到其他页面。

$(document).on('click', "#only_available", function () {
if ($('#only_available').is(':checked')) {
var status = 1;
} else {
var status = 0;
}
var params = window.location.search;
var path = window.location.pathname;
var old_url = path+params;
var url = old_url+'&status=' + status;
window.history.pushState("", "", url);
$.ajax({
url: url,
type: "GET",
cash: false,
success:
function (response) {
$('#products-load').html(response);
}
});
});
});

最新更新