简体   繁体   中英

Passing Url params from one page to another

So I have a filter form on a page that show paginated results. Currently when you apply the filter settings using a get request everything works but when you try to switch pages it resets. I have thought of passing a url from one page to another using a script like the one below. This copies the url but does not actually change the page, just copies the string. You can see in the urls below that the url does change page but the actual webpage stay on the first page regardless of the url. I am using Django and Django filters. Maybe a there is a better jQuery solution, Any suggestions?

script

document.querySelectorAll('.fqs')
    .forEach((el) => el.attributes.href.value += window.location.search);

Url

Without script:

/relations/?createdBy=&occursIn=&createdAfter=&createdBefore=&terminal_nodes=&project=1

With Script:

/relations/?page=2?createdBy=&occursIn=&createdAfter=&createdBefore=&terminal_nodes=&project=1

Next Page Link

<a class="fqs" href="?page={{ relations.next_page_number }}">Next &raquo;</a>

Url when pressing previous button

?page=1&page=2&createdBy=&occursIn=&createdAfter=&createdBefore=&terminal_nodes=&project=1

If I understand correctly you're adding pagination server-side ?page={{...}} and you adding already existing url parameters via js.

The resulting urls have two ? in it which may be why the link doesn't give you the correct page.

location.search includes the ? so to add that to your ?page=x you'd have to replace ? with & :

document.querySelectorAll('.fqs')
    .forEach((el) => el.attributes.href.value += window.location.search.replace("?", "&"));

EDIT: if this works it may stop working on next pages as location.search would then include page=x giving duplicate page query parameters.

To filter out page parameter from location.search you could do something like:

document.querySelectorAll('.fqs')
  .forEach((el) => {
    var params = window.location.search.replace("?", "&").split("&");
    params = params.filter((v) => v.indexOf("page") == -1).join("&");
    el.attributes.href.value += params;
  });

BTW, note that arrow functions don't work in legacy browsers like IE11.

In order to accomplish this I decide to not use any javascript at all and use python instead. I added

gt = request.GET.copy()
if 'page' in gt:
    del gt['page']

    context = {
        'paginator': paginator,
        'relations': relations,
        'params': urlencode(gt),
        'filter': filtered,
        }

to my view. It copies the params, then deletes the param matching page and encodes in the context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM