如何发送REST调用,并将返回json和结果



当有人写下名字并点击搜索按钮时,我想从外部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"
}

]

为了演示,有必要将源代码替换为占位符。

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>

在"//用myJson做点什么"之后你可以做:

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">

最新更新