Javascript-从输入提交中加载URL,而不用“返回:false;”

时间:2018-07-15 19:36:10

标签: javascript

我有这种在提交时执行blogSearch()的表单:

<form onsubmit="return blogSearch();">
  <input class="mb0" type="text" id="blogsearchinput" placeholder="Search..." />
</form>

这是我的JavaScript:

function blogSearch() {
  var test = document.getElementById("blogsearchinput").value
  window.location.href = "../list.php";
  return false;
}

我想在页面加载后在BlogSearch()函数中运行更多的javascript,但是很明显,在返回false之后我不能这样做。仅当我返回false时,页面才会加载,因为我读到它将覆盖默认的输入提交。

是否有一种方法可以从输入提交中加载URL而无需返回false?或者以某种方式可以在加载后继续运行函数?

1 个答案:

答案 0 :(得分:0)

您无法使用window.location在同一页面上显示搜索结果, 带您到另一个页面。在这种情况下,您可能要使用 XHR request至 获取数据,然后将其显示在同一页面上。

我对HTML做了一些修改:

<form id="search-form">
  <label>Search blog: <input class="mb0" type="search" id="search-query"></label><input type="submit" value="Search">
</form>
<ul id="search-results"></ul>

然后在list.php中,您将执行以下操作:

<?php
// get the q parameter that we will be setting in our XHR request
$query = isset($_GET['q']) ? $_GET['q'] : '';

// I'm assuming you are returning a list of links, so I'm creating an
// array of associative arrays that contain url and link name info.
// In your actual application you would probably be pulling this data from a
// database instead, using the $query variable to filter the results that the DB
// returns. I would recommend using prepared statements to avoid SQL injection
// attacks. My PHP is really rusty right now so I'm not going to attempt to
// filter this array and just return the whole thing.
$results = array(
  array('name' => 'Foo', 'url' => '/foo'),
  array('name' => 'Bar', 'url' => '/bar'),
  array('name' => 'Baz', 'url' => '/baz'),
);

// encode our array as JSON so we can easily decode it in JavaScript
echo (json_encode($results));
?>

然后,这是您用来发出请求并显示结果的JS。

// cache elements we will be using in variables
const searchForm = document.getElementById("search-form");
const searchQuery = document.getElementById("search-query");
const searchResults = document.getElementById("search-results");

// this function will do the XHR request and display the results
function blogSearch(event) {

  // stops the default action, in this case submitting the form to the server
  event.preventDefault();

  // get the query and build a url to request
  let query = searchQuery.value;
  let url = `../list.php?q=${query}`;

  let displayError = () => {
    searchResults.innerHTML = '<li>There was an error retrieving your search results</li>';
  };

  let request = new XMLHttpRequest();
  request.open('GET', url, true);

  request.onload = () => {
    if (this.status >= 200 && this.status < 400) {
      // parse the JSON data that was returned
      let data = JSON.parse(this.response);

      // build up a list of li element containing links
      let html = ''
      data.forEach(item => {
        html += `<li><a href="${item.url}">${item.name}</a></li>`;
      });
      // display the search results in our unordered list
      searchResults.innerHTML = html;

    } else {
      displayError();
    }
  };

  request.onerror = () => {
    displayError();
  };

  request.send();
}

// attach the event to the search form
searchForm.addEventListener('submit', blogSearch, false);

关于我所做的更改的一些注释:

进一步阅读