一旦按下提交按钮,我的Javascript加载程序是否有一种激活方法?

时间:2019-05-29 16:25:28

标签: javascript jquery html css

我正在建立一个youtube mp4和mp3下载器网站,当有人提出从youtube帖子中获取数据的请求时,加载它大约需要3-5秒。我可以在JavaScript中使用这段代码以使其正常运行吗?

到目前为止,我已经将此代码脚本放置在JavaScript中的各种功能中。除非我的代码完全错误,否则任何方法都不会起作用。

$("#results-list").append("<li>searching for video</li>").show();

我希望一旦发现视频数据隐藏,JavaScript加载器就会显示“正在搜索视频”

"use strict";

String.prototype.trunc = function(n) {
  return this.substr(0, n - 1) + (this.length > n ? "&hellip;" : "");
};

// using apiKey for youtube api
const apiKey = "ABCxyz";
const searchURL = "https://www.googleapis.com/youtube/v3/search";

function formatQueryParams(params) {
  const queryItems = Object.keys(params).map(
    key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`
  );
  return queryItems.join("&");
}

//Display results of youtube search
function displayResults(responseJson) {
  // if there are previous results, remove them
  console.log(responseJson);
  $("#results-list").empty();

  $("#results-list").append(`<li><img src="${responseJson.thumbnail}" alt="thumbnail for ${responseJson.title}" class="thumbnail"></li>`);
  $("#results-list").append(`<li><p>${responseJson.title.trunc(128)}"</p></li>`);
  $("#results-list").append(`<li class=" audio-dl"><button class="w3-button w3-black w3-round audio-dl"><a href="${responseJson.audio}" download><i class="fa fa-download"></i> Mp3 Audio Download</a></button></li>`);
  $("#results-list").append(`<li class="video-dl"><button class="w3-button w3-black w3-round video-dl"><a href="${responseJson.video}" download><i class="fa fa-download"></i> Mp4 Video Download</a></button></li>`);

  //display the results section
  $("#results").removeClass("hidden");
}

//initiate youtube download
function downloadVideo(videoId) {
  console.log(videoId);
  return fetch(`https://getvideo.p.rapidapi.com/?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D${videoId}`, {
    headers: {
      "X-RapidAPI-Host": "getvideo.p.rapidapi.com",
      "X-RapidAPI-Key": "d390d7b0e9mse"
    }
  }).then(function(response) {
    return response.json();
  }).then(function(data) {
    console.dir(data);
    if (!data.streams) {
      throw new Error("Error retrieving download URL, try a different video!");
    }
    return {
      audio: data.streams.filter(stream => {
        return stream.format === "audio only";
      })[0].url,
      video: data.streams.filter(stream => {
        return stream.format !== "audio only";
      })[0].url,
      thumbnail: data.thumbnail,
      title: data.description
    };
  });
}

function getYouTubeVideos(query) {
  const params = {
    key: apiKey,
    q: query,
    part: "snippet"
  };
  const queryString = formatQueryParams(params);
  const url = searchURL + "?" + queryString;
  console.log(url);

  $("#js-error-message").text("");

  fetch(url).then(response => {
    if (response.ok) {
      return response.json();
    }
    throw new Error(response.statusText);
  }).then(responseJson => downloadVideo(responseJson.items[0].id.videoId)).then(download => displayResults(download)).catch(err => {
    $("#js-error-message").text(`Something went wrong: ${err.message}`);
  });
}

//submit button push
function watchForm() {
  $("form").submit(event => {
    event.preventDefault();
    const searchTerm = $("#js-search-term").val();
    //const maxResults = $("#js-max-results").val();
    getYouTubeVideos(searchTerm);
    console.log(searchTerm);
    $("#results-list").append("<li>searching for video</li>").show();
  });
}

$(watchForm);
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css" />
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>

<header class="header">
  <div id="logo">
    <img src="img\logo.png" alt="logo" />
  </div>
  <nav class="dark-red"></nav>
</header>
<main>
  <section class="input-group">
    <div class="main">
      <h1 class="finder-heading">Download a Youtube video</h1>
      <form id="js-form">
        <label for="search-term"></label>
        <input class="search-input" type="text" name="search-term" id="js-search-term" required placeholder="       Paste link here https://youtu.be/sC11wWvQ7hE" />

        <label for="max-results"></label>

        <input class="go-button" type="submit" value="Download Now" />
      </form>
      <section class="error-results">
        <p id="js-error-message" class="error-message"></p>
      </section>
      <div class="cc-notice">
        <b>Example:</b> https://youtu.be/7_S1bxrZZOk <br />
        <b>or type a title:</b> Goalden Chyld - Focus Freestyle
      </div>
    </div>
  </section>

  <section id="results" class="hidden">
    <h2>Search result</h2>
    <ul id="results-list" class="w3-bar"></ul>
  </section>

  <section class="instruction-body">
    <div class="intstruction-content">
      <div class="instruction-head">
        <h3>How to Download Youtube Videos</h3>
        <p>
          Paste the URL of Video from YouTube or type the title of a video you want into the field above.
        </p>
      </div>
      <div class="instruction-box">
        <div class="instruction-box-image">
          <img src="img\Folder-Links.png" alt="twitter video downloader" width="110" height="110" />
        </div>
        <div class="instruction-box-header">
          <div class="instruction-box-heading">Copy the Video URL</div>
          <div class="instruction-box-description">
            Find the YouTube video that you want to download and copy its link.
          </div>
        </div>
      </div>
      <div class="instruction-box">
        <div class="instruction-box-image">
          <img src="img\browser.png" alt="twitter video downloader" width="110" height="110" />
        </div>
        <div class="instruction-box-header">
          <div class="instruction-box-heading">
            Paste URL into Search Box
          </div>
          <div class="instruction-box-description">
            Next, paste the video's link into the search field above, then click the Download button.
          </div>
        </div>
      </div>
      <div class="instruction-box">
        <div class="instruction-box-image">
          <img src="img\download-arrow.png" alt="twitter video downloader" width="110" height="110" />
        </div>
        <div class="instruction-box-header">
          <div class="instruction-box-heading">
            Download and Save Video
          </div>
          <div class="instruction-box-description">
            Click the Download button to save the Youtube video to your computer.
          </div>
        </div>
      </div>
    </div>
  </section>
  <section></section>
</main>
<footer class="footer">
  <section>
    <p class="footer-right">
      Copyright © 2019 U Tube Grabber. All rights reserved.
    </p>
  </section>
  <section class="footer-left">
    <p>Created by David Piper</p>
  </section>
</footer>

0 个答案:

没有答案