【问题标题】:Fetching data from backend to create a dropdown list in Javascript从后端获取数据以在 Javascript 中创建下拉列表
【发布时间】:2021-07-31 22:56:45
【问题描述】:

这是我的课程容器 sn-p。我想通过从后端获取数据来创建所有课程的下拉列表(URL:https://ffcc-app.herokuapp.com/get/courses) 在sn-p中,我手动放了一些虚拟课程

<div class="container">
        <form action="#" method="POST">
        <h2>Course 1</h2>
        <div class="select-box">
          <div class="options-container">
            <div class="option">
                <input type="radio" class="radio" id="film" name="category" value="film" />
                <label for="Course 2">Course 1</label>
              </div>
            <div class="option">
              <input type="radio" class="radio" id="dance" name="category" value="dance" />
              <label for="Course 2">Course 2</label>
            </div>
            <div class="option">
              <input type="radio" class="radio" id="science" name="category" value="science" />
              <label for="Course 3">Course 3</label>
            </div>
            <div class="option">
              <input type="radio" class="radio" id="art" name="category" value="art"/>
              <label for="Course 4">Course 4</label>
            </div>
            <div class="option">
              <input type="radio" class="radio" id="music" name="category" value="music"/>
              <label for="Course 5">Course 5</label>
            </div> 
            
          </div>
          <div class="selected">
            Select Courses
          </div>
          <div class="search-box">
            <input type="text" placeholder="Search..." />
          </div>
        </div>
</div>        

我创建了一个搜索框来过滤课程列表并在您键入任何字符时显示过滤后的列表。 当您选择任何课程时,应将“Selected”类值替换为所选课程的名称

我尝试使用 Fetch API 从后端获取数据,这是我的代码 sn-p

const point = 'https://ffcc-app.herokuapp.com/get/courses';

let courses1 =[];

fetch(point)
    .then(response => response.json())
    .then(data => courses1=data.courses)

function findMatches(wordToMatch , courses1){
    return courses1.filter(function place(a){
        const regex = new RegExp(wordToMatch,'gi')
        return a.code.match(regex) || a.title.match(regex)
    });
}

function displayMatches(){
    const matchArray = findMatches(this.value, courses1)
    const html = matchArray.map(place => {
        const regex = new RegExp(this.value, 'gi');
        const code = place.code.replace(regex, `<span class="hl">${this.value}</span>`);
        const title = place.title.replace(regex, `<span class="hl">${this.value}</span>`);
        return `
        <div class="option">
              <input type="radio" class="radio" name="category" />
              <label for="course-1"> ${code} , ${title} , ${place.credits} , ${place.type}</label>
        </div>
        `
    }).join("");
    opt.innerHTML = html;
}
const search = document.querySelector(".search-box");
const opt = document.querySelector(".options-container");
search.addEventListener("change",displayMatches);
search.addEventListener("keyup",displayMatches);

虽然我能够获取它,但我没有得到我想要的输出,我也想不出用课程值替换“选定”类值的方法。

有人可以帮助我吗?如果您也使用 Fetch API 来获取数据,我将不胜感激。

【问题讨论】:

  • 您能否详细说明发生了什么?您看到的是什么而不是“所需的输出”。我的第一个猜测是,当您尝试使用“courses1”数组时,它还没有准备好。您是否收到任何错误消息?
  • 不,我没有收到任何错误消息,而是收到所有 1514 课程列表,但是当我输入任何字符时,它没有被过滤,而且我无法替换“已选择" 课程名称的类值。

标签: javascript fetch-api


【解决方案1】:

我没有足够的时间给你一个完整的解决方案或详细的解释,但我希望这可以帮助你入门: 这是一个工作示例,它获取数据并对其进行过滤,并返回标题或代码与搜索字符串匹配的课程(我认为这是您的代码遇到的问题)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <script>
    const endpoint = 'https://ffcc-app.herokuapp.com/get/courses';
    let courses = [];

    // if you don't know about async/await, check it out, it's pretty neat!
    async function main() {
      const response = await fetch(endpoint);
      const data = await response.json();
      courses = data.courses;

      console.log(findCourses("Lean Start-up Management"));
    }

    function findCourses(search) {
      const norm_search = search.toLowerCase();
      return courses.filter(course => {
        return course.title.toLowerCase().includes(norm_search) ||
               course.code.toLowerCase().includes(norm_search);
      })
    }

    main();
  </script>
</body>
</html>

【讨论】:

    猜你喜欢
    • 2021-10-08
    • 2021-10-13
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-23
    相关资源
    最近更新 更多