简体   繁体   中英

../path is not redirecting page

I'm trying to the page to search.html . Depending on what page it is, search.html is either located in the same directory or a directory above. I can't figure out why it's not redirecting.

Here is HTML code:

  <form  class="search" onsubmit="searchSite()">
    <input id="search" title="Seach this site" type="text" name="search"
      placeholder="Search this site..">
  </form>

Here is JS code:

function searchSite() {
  var search = document.getElementById("search").value.toLowerCase().split(" ");
  searchArticles(search);
  displayResults();
}

function displayResults() {
  if (window.location.href.indexOf("humans") !== -1 
      || window.location.href.indexOf("other")){ 
    window.location.href = "../search.html";
    console.log(window.location.href);}
  else
    window.location.href = "search.html";
}

Before searching the URL is: file:///C:Desktop/comp266/unit5/public_html/other/other.html

After searching the URL is: file:///C:Desktop/comp266/unit5/public_html/other/other.html ?search=good

But I want the URL to be: file:///C:Desktop/comp266/unit5/public_html/search.html

This is because form has its default behavior that redirect site to form's action URL or query URL with query params as you see.
You can prevent this default behavior by return false on submit listener:

  <form  class="search" onsubmit="return searchSite()"> <!-- ADD THIS -->
    <input id="search" title="Seach this site" type="text" name="search"
      placeholder="Search this site..">
  </form>
function searchSite() {
  var search = document.getElementById("search").value.toLowerCase().split(" ");
  searchArticles(search);
  displayResults();

  // ADD THIS
  return false;
}

A more proper way is do preventDefault in case there may be bug occurs before return false:

<form  class="search" onsubmit="return searchSite(event)"> <!-- ADD THIS -->
    <input id="search" title="Seach this site" type="text" name="search"
      placeholder="Search this site..">
  </form>
function searchSite(event) {
  // ADD THIS
  event.preventDefault();

  var search = document.getElementById("search").value.toLowerCase().split(" ");
  searchArticles(search);
  displayResults();

  // ADD THIS
  return false;
}

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