【发布时间】: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