<form id='result2'>方法2</form>
<script>
  fetch('http://127.0.0.1:9999/getAudio', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  })
    .then(response => response.json())
    .then(response => document.getElementById('result2').innerHTML = response.Rescoring_result)
    .catch(error => console.error(error))
</script>
<p>需要修改两个地方:</p>
<ol>
<li>在 fetch 请求中添加 headers,指定请求和响应的数据类型为 JSON:</li>
</ol>
<pre><code class="language-javascript">fetch('http://127.0.0.1:9999/getAudio', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  }
})
</code></pre>
<ol start="2">
<li>在第二个 then 中,不需要再使用 JSON.parse 解析响应,因为 headers 中已经指定了响应的数据类型为 JSON,fetch 会自动将响应解析为 JSON 对象:</li>
</ol>
<pre><code class="language-javascript">.then(response =&gt; document.getElementById('result2').innerHTML = response.Rescoring_result)
</code></pre>
<p>完整代码如下:</p>
<pre><code class="language-html">&lt;form id='result2'&gt;方法2&lt;/form&gt;
&lt;script&gt;
  fetch('http://127.0.0.1:9999/getAudio', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  })
    .then(response =&gt; response.json())
    .then(response =&gt; document.getElementById('result2').innerHTML = response.Rescoring_result)
    .catch(error =&gt; console.error(error))
&lt;/script&gt;
</code></pre>
JavaScript fetch API 获取 JSON 数据并显示在页面上

原文地址: https://www.cveoy.top/t/topic/lBfu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录