如何从curlapi连续填充html文本框

sczxawaw  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(312)

我有一个html文本框,我想用从api调用接收的数据填充它 curl 命令。我使用的curl api以以下格式连续返回/livestreams数据:

curl <api_endpoint>

data: value1
data: value2
data: value3

我希望livestream在点击按钮时显示在html文本框中。我的html、js如下所示:

<html>
<textarea rows='14' id="value" placeholder="anything you want here"></textarea>
<button class="get_values" onclick="return get()">GET</button>
</html>

<script>

const getButton = document.querySelector('.get_values');

getButton.addEventListener('click', function(e) {
  #fill the textbox from curl command livestream
});

</script>

我如何用一个文件中的数据流填充文本框 curl <api_endpont> 命令?不需要websocket,我已经在使用的api实时连续地流式传输/发送数据,我只需要调用并填充文本框。

hgb9j2n6

hgb9j2n61#

您只需通过 GET 请求,并使函数在指定的时间间隔内重复自身。也 onclick on按钮已经添加了一个事件侦听器,因此代码应该是这样的。

<html>
<body>
<textarea rows='14' id="value" placeholder="anything you want here"></textarea>
<button class="get_values" onclick="startUpdate(event)">GET</button>

<script>
// to set an update interval at every 2 sec(2000ms)
function startUpdate(e) {
  // e. preventDefault();
  // calling instantly
  updateTextArea();
  // and setting interval
  window.setInterval(updateTextArea, 2000);
}

// defining global variable, to display dynamic update
window.counter = 1

function updateTextArea() {
  let url = "https://jsonplaceholder.typicode.com/todos/" + window.counter; // test url
  // assuming data is json, if it is text use response.text()
  fetch(url)
    .then(response => response.json())
    .then(data => {
      let textArea = document.getElementById("value");
      // parsing the JSON value to string
      textArea.value = JSON.stringify(data);
    })
  window.counter = window.counter + 1; // increment counter
}
</script>
</body>
</html>

编辑:要传递事件,您应该传递关键字 event 在onclick函数调用中。

相关问题