简体   繁体   中英

Page will refresh instead of redirecting

I have an HTML file that looks like the following:

<form onSubmit="getSearchResults()">
  <input id="search-query" type="text" placeholder="Search">
  <button onclick="getSearchResults()"></button>
</form>

<script type=text/javascript>
  var searchURL = "{% url 'search' %}" // I'm using Django, and this gets me the correct URL

  function getSearchResults(){
    var searchQuery = document.getElementById('search-query').value;
    if (searchQuery.length > 0)
        self.location.href = searchURL + '?' + searchQuery;
    else
        self.location.href = searchURL;
    return false;
  }

</script>

The idea is that every time I submit the form or click on the button, I want the page to be redirected to a different URL.

Right now, on either form submit or button click, the page just reloads. I looked at my console in Firefox and it says:

Navigated to http://localhost:8000/search
Navigated to http://localhost:8000/

So I know that my URL is correct and my code works somewhat because I am being navigated to the correct place, but then I'm being navigated to the original page I was on.

I have also tried:

window.location.href
location.href
<form onsubmit="return getSearchResults()">

Note return . This tells the onsubmit function to return what getSearchResults() returns. Otherwise return false; doesn't do anything.

Other approaches like e.preventDefault() work too.

Since the button is in a form, it submits the form. Try adding e.preventDefault() inside the handler:

function getSearchResults(e) {
  e.preventDefault();
  var searchQuery = document.getElementById('search-query').value;
  if (searchQuery.length > 0)
    self.location.href = searchURL + '?' + searchQuery;
  else
    self.location.href = searchURL;
  return false;
}

Page submits due to default type of the button.

<button type="button" ...

or

<button onclick="return getSearchResults()"></button>

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