javascript - 如何发送 REST 调用并返回 json 和结果?

标签 javascript json rest search

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

关于javascript - 如何发送 REST 调用并返回 json 和结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58563539/

相关文章:

java - 为什么使用 POST 方法的 Java HttpURLConnections 会导致返回 Http 500 错误?

python - 在 Python 中编写从 SPARQL 查询返回的 JSON 数据的正确方法

java - 如何在android中解析这个JSON(从.NET webservice返回)

javascript - 如何映射此 Json 以与 Handlebars js 一起使用?

javascript - 在没有特殊字符的情况下粘贴到文本区域

rest - CFHTTP HTTPS 连接失败 CF8

mysql - 在 Web api 中使用日期时间

javascript - Firefox 上的嵌套 z-index 问题,较高的 z-index 落后于较低的 z-index

javascript - 如何为移动浏览器添加 pdf 查看器到网站

javascript - 在 dojo 小部件中混合多个模板