Why the request of index.js was not successful? console.log (search) was refreshed immediately under the console print. What is the reason for this?

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <div>
    <form id="myform">
      <div class="input-field">
        <input type="search" id="books">
        <label for="search">Search books</label>
      </div>
      <button class="btn red"></button>
    </form>
  </div>
  <div class="result">

  </div>
  <script src="https://cdn.bootcss.com/jquery/3.3.0/jquery.min.js"></script>
  <script src="https://cdn.bootcss.com/materialize/1.0.0-beta/js/materialize.min.js"></script>
  <script src="index.js"></script>
</body>
</html>

index.js:

$(document).ready(function() {
  console.log("jQuery sucessful")
  $("-sharpmyform").submit(function() {
    var search = $("-sharpbooks").val();
    console.log(search);
    if(search === "") {
      alert("Please enter something");
    }else {
      var url = "";
      var img = "";
      var title = "";
      var author = "";

      $.get("https://www.googleapis.com/books/v1/volumes?q=" + search,function(res) {
        console.log(res);
      });
    }
  });

  return false;
});

  1. first of all, an obvious problem, as mentioned by Ls, is that your return false; statement is outside the callback function of .submit () , so it fails to prevent the default event from being triggered, which leads to abnormal page redirection.
  2. there are usually two ways to block default events in callbacks: the first is to write return false; at the end of the callback, of course, you can also write return a Boolean variable. In this case, you will decide whether to block the default behavior of events based on the value of this Boolean variable. Second, in fact, Ls has also mentioned that the event object e is passed in at the beginning of the callback (of course, sometimes it will be ev , evt , event , etc.), and then call .implementDefault () to achieve the purpose of blocking the default behavior of the event, and this sentence can be placed at the beginning of the callback, such as

    .
    $("-sharpmyform").submit(function() {
        //your code....
        return false;
    });
Menu