21

I have a seemingly simple question, but can't find the answer. I have a webpage, which may have resulted from a POST request and may have an anchor (#) in the URL. I want to reload this page as a GET request in JavaScript. So it's similar to this question, but I actually want to avoid the POST, not just the warning about it.

So, for example, if the page resulted from a POST request to "http://server/do/some?thing#" I want to reload the URL "http://server/do/some?thing" as a GET. If I try

window.location.reload(true);

that causes IE to try a POST. If I instead do:

window.location = window.location.href;

this does nothing when the URL has an anchor. Do I really need to do string manipulation myself to get rid of the "#whatever" or is there an easier, "better" way to do this?

Community
  • 1
  • 1
EMP
  • 59,148
  • 53
  • 164
  • 220
  • 3
    The "proper" way probably involves not doing a client-side page refresh. – Kenan Banks Aug 04 '09 at 01:24
  • Indeed, can you provide a little more context about the problem so that we know we're not about to reccomend you do something stupid. – Breton Aug 04 '09 at 03:10
  • possible duplicate of [Refresh the page with javascript and GET variables](http://stackoverflow.com/questions/17253754/refresh-the-page-with-javascript-and-get-variables) – Stephen Dec 02 '14 at 14:49

3 Answers3

22

The best I've come up with so far is:

function reloadAsGet()
{
    var loc = window.location;
    window.location = loc.protocol + '//' + loc.host + loc.pathname + loc.search;
}
EMP
  • 59,148
  • 53
  • 164
  • 220
10

Try the following:

location.replace(location.href)
Alex Salauyou
  • 14,185
  • 5
  • 45
  • 67
Sergey Lokot
  • 101
  • 1
  • 3
1

You can try this

location=location.href
Sarath Ak
  • 7,903
  • 2
  • 47
  • 48
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Badacadabra May 27 '17 at 13:03
  • No-no-no, do it the right way: `location.assign(location.href);` – AlexMelw Jan 25 '22 at 11:19