【问题标题】:How to filter form input data with json data in plain javascript?如何在纯javascript中使用json数据过滤表单输入数据?
【发布时间】:2019-10-26 10:54:13
【问题描述】:

如果我在输入表单字段中键入标题名称,我对如何获取特定结果感到困惑。以下是我尝试过的代码。我会很感激的。谢谢

index.html 文件

<form method="POST">
 <input type="text" id="searchName" class="form-control" placeholder="Lorem name">
<button  onclick="userAction(event)" class="search-icon"><img src="images/icon.png" alt="submit"></button>
  </form>

<ul id="list">

</ul>





JavaScript File
const list = document.getElementById('list');
const searchName = document.getElementById('searchName').value;

const userAction = async (event) => {
  event.preventDefault();
      fetch('https://jsonplaceholder.typicode.com/todos')
  .then(response => response.json())
  .then(todos => {
    todos.forEach((todo) => {
    if(todo===searchName){
      const li = document.createElement('li');

      li.innerHTML = li.innerHTML = `${todo.userId} ${todo.id} ${todo.title} ${todo.completed}`;

      list.appendChild(li);
    }
    });
  })
}

【问题讨论】:

  • 您的 API 是否允许您将搜索作为参数提交,以便它只返回与搜索字符串匹配的数据? fetch('http://jsonserver.com?search=searchName') 例如。那会更好。然后你可以迭代返回的数据,知道它是正确的。
  • @Andy 感谢您的回复。能不能写一些,我能理解。谢谢
  • 我也刚刚更新了我的代码。
  • 如果您的 JSON 服务不处理 URL 参数,那就没有意义了。

标签: javascript html json rest


【解决方案1】:

#searchName 在页面加载时没有值,并且您没有更新函数内部的值,因此如果条件失败。

您应该在函数内部获取搜索值。

const list = document.getElementById('list');
const userAction = async (event) => {
  list.innerHTML = ''; //clear the content on each click
  event.preventDefault();
  const searchName = document.getElementById('searchName').value.trim();
  fetch('https://jsonplaceholder.typicode.com/todos')
  .then(response => response.json())
  .then(todos => {
    todos.forEach((todo) => {
      if(searchName == todo.title){
        const li = document.createElement('li'); 
        li.textContent = `${todo.userId} ${todo.id} ${todo.title} ${todo.completed}`;
        list.appendChild(li);
      }
    });
  })
}
<form method="POST">
 <input type="text" id="searchName" class="form-control" placeholder="Lorem name">
<button  onclick="userAction(event)" class="search-icon"><img src="images/icon.png" alt="submit"></button>
  </form>

<ul id="list">

</ul>

【讨论】:

  • 感谢您的回复 Mamun。当我在输入字段中输入 delectus aut autem 时,我只是运行代码 sn-p 然后它不显示与此相关的数据,而是显示所有 json 数据。请帮助。谢谢
  • @Yasir,你必须检查像if(searchName == todo.title){...这样的对象的title属性,更新答案,请检查:)
  • 我也刚刚更新了我的代码。错误地,我错过了一点..
  • 你能编辑你的代码sn-p吗。这样我更容易理解..
  • @Yasir,但如果我在输入中输入 delectus aut autem 我会得到 1 1 delectus aut autem false...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-23
  • 1970-01-01
  • 2020-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-02
相关资源
最近更新 更多