[当有人写下姓名并单击搜索按钮时,我想将搜索结果从外部result.json文件显示到无序列表中。我只是在如何获取结果并显示到列表中遇到问题。请帮助我。我会很感激的。下面是我的代码。
index.html文件
<form method="POST">
<label>Search</label>
<input type="text" id="Search" />
<input type="submit">
</form>
<!-----Show result here-->
<ul>
<li>
</li>
</ul>
<script>
const userAction = async () => {
const response = await fetch('test.json', {
method: 'POST',
body: myBody, // string or object
headers: {
'Content-Type': 'application/json'
}
});
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
}
</script>
result.json file
[
{
"id":1,
"name":"John",
"City":"Melbourne",
"state":"VIC"
}
]
var myListElement = document.getElementById("myList");
myListElement.innerHTML = '<li>Id: '+ item.id +'</li>' + '<li>Name: '+ item.name +'</li>' + '<li> City: '+ item.City +'</li>' + '<li>State: '+ item.state +'</li>';
并且在之后:您可以像这样编辑您的元素:
<ul id="myList">
const list = document.getElementById('list');
const userAction = async (event) => {
event.preventDefault();
fetch('https://jsonplaceholder.typicode.com/todos')
.then(response => response.json())
.then(todos => {
todos.forEach((todo) => {
const li = document.createElement('li');
li.innerHTML = `${todo.userId} ${todo.id} ${todo.title} ${todo.completed}`;
list.appendChild(li);
});
})
}
<form method="POST" onsubmit="userAction(event);">
<label>Search</label>
<input type="text" id="Search" />
<input type="submit">
</form>
<!-----Show result here-->
<ul id="list"></ul>