简体   繁体   中英

Change url after successfully submitting a form through AJAX with a GET method

I need to change the current url after a form has been submitted using an AJAX GET request.

I've tried to use history.pushState(null, null, url+'?'+form.serialize()) and it works fine. The problem is that what I'm retrieving is only a subset of the page, therefore the browser will display that subset instead of the whole page when navigating through history.

I like history.pushState approach, but it doesn't look viable; do you know any better way? Or, even better, do you know how to save the whole content of the page instead of the subset?

The url I need to get is mydomain.com/some-page?variable=1&varialbe_2=2

To give you more informations: the controller method I need to access detects if the route has been called by an Ajax request, and if it has the response will be json. Otherwise it will load the whole page normally.

Thanks for any help you can give.

If you just want to change the current page, the following will do the trick:

window.location.href = url+'?'+form.serialize()

If you want to persist page states you could also use localstorage or sessionstorage to save the data, then just check and load it when the page opens. It won't be easy to share (query strings in URLs are easy to copy and paste) but will allow you to persist a lot more data.

If you are trying to reload just one element on the page, then push state is exactly what you are looking for, you just need to respond to the user navigating backwards.

From another SO Answer :

window.onpopstate = function(event)
{
    alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
};

This will allow you to execute code to grab the contents of the URL and manually update your UI to reflect the previously persisted data.

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