簡體   English   中英

如何將表單/輸入/文本添加到 fetch() 請求的末尾?

[英]How to add a form/input/text to end of fetch() request?

我正在構建一個隨機的 DogAPI 圖像生成器,您將 1-50 之間的數字放入表單文本框中,然后點擊發送,它會返回您輸入到打印到控制台的(鏈接)圖像中的數字。 我可以手動將數字放在提取的末尾,並將該數量打印到控制台,但是我無法連接您在表單中輸入的數字以將其放在提取請求的末尾。

我試過使用模板文字。 如果您在提取結束時手動輸入 ${5},它會向控制台打印 5 個圖像。 偉大的! 但是......我如何使用模板文字將我在表單中放入的內容連接到獲取的末尾。 ${text} 顯然不起作用! 還是我做錯了? 謝謝大家的幫助!

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>How Many?</title>
    <link rel="shortcut icon" href="#">
    <link rel="stylesheet" href="index.css">
</head>
<body>
    <div class="container">
        <h1>How Many Dog Pics Do You Want?</h1>

        <form>
          <input type="text" placeholder="1-50?">
          <input type ="submit" value="Send">
        </form>
    </div>
    <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
    <script src="index.js"></script>
</body>
</html>

CSS:

* {
  box-sizing: border-box;
}

body {
  font-family: 'Roboto', sans-serif;
}

.container {
  max-width: 600px;
  margin: 0 auto;
}

JS:

'use strict';

function getDogImage() {
  fetch(`https://dog.ceo/api/breeds/image/random/${text}`)
    .then(response => response.json())
    .then(responseJson => console.log(responseJson));
}

function watchForm() {
  $('form').submit(event => {
    event.preventDefault();
    getDogImage();
  });
}

$(function() {
  console.log('App loaded! Waiting for submit!');
  watchForm();
});

您需要從輸入中獲取值(使用.val() ),並將其傳遞給getDogImage(text) (請參閱代碼中的注釋):

 function getDogImage(text) { // add the text parameter fetch(`https://dog.ceo/api/breeds/image/random/${text}`) .then(response => response.json()) .then(responseJson => console.log(responseJson)); } function watchForm() { $('form').submit(event => { event.preventDefault(); var text = $('.number').val() || 3; // get the text from the input or use 3 getDogImage(text); // pass to getDogImage }); } $(function() { console.log('App loaded! Waiting for submit!'); watchForm(); });
 * { box-sizing: border-box; } body { font-family: 'Roboto', sans-serif; } .container { max-width: 600px; margin: 0 auto; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container"> <h1>How Many Dog Pics Do You Want?</h1> <form> <input class="number" type="text" placeholder="1-50?"> <input type="submit" value="Send"> </form> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM