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

问题描述 投票:0回答:2

[当有人写下姓名并单击搜索按钮时,我想将搜索结果从外部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"

 }


]
javascript json rest search
2个回答
0
投票
仅在“ //用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">


0
投票
为了演示,有必要用占位符替换您的源。

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>
© www.soinside.com 2019 - 2024. All rights reserved.