<form id='result2'></form>
<script>
  fetch('/getAudio',{method:'POST'})
    .then(response => response.json())
    .then(response => document.getElementById('result2').innerHTML = response['Rescoring_result'])
    .catch(error => console.error(error))
</script>
<p>以下是经过调试的代码:</p>
<pre><code>&lt;form id='result2'&gt;&lt;/form&gt;
&lt;script&gt;
  fetch('/getAudio',{method:'POST'})
    .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>
<p>主要的更改有两处:</p>
<ol>
<li>第一次 .then() 中将 response 进行 json 解析,即 response.json()。</li>
<li>第二次 .then() 中使用 response['Rescoring_result'] 来获取返回结果。</li>
</ol>
<p>解释:</p>
<ol>
<li>fetch() 函数返回的是一个 Promise 对象。第一个 .then() 中的箭头函数的参数 response 就是 fetch() 请求得到的响应对象。</li>
<li>在第一个 .then() 中,使用 response.json() 将响应对象转换为一个 JSON 格式的对象,以便后续处理。</li>
<li>在第二个 .then() 中,使用 response['Rescoring_result'] 来获取 JSON 对象中的 Rescoring_result 属性,并将其赋值给表单元素的 innerHTML 属性,以展示返回结果。</li>
<li>如果请求失败,则会执行 .catch() 中的箭头函数,输出错误信息到控制台。</li>
</ol>
JavaScript fetch() 请求调试:解析 JSON 数据并提取属性

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

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