【问题标题】:How to continuously populate HTML textbox from curl API如何从 curl API 连续填充 HTML 文本框
【发布时间】:2021-03-27 08:07:45
【问题描述】:

我有一个 HTML 文本框,我想用curl 命令从 API 调用接收到的数据填充该文本框。 我正在使用的 curl API 以以下格式连续返回/直播数据:

curl <api_endpoint>

data: value1
data: value2
data: value3

我希望在单击按钮时在 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 &lt;api_endpont&gt; 命令的数据流填充文本框? 不需要 websocket,我正在使用的 API 已经实时连续流/发送数据,我只需要拨打电话并填写文本框。

【问题讨论】:

  • 您需要一个支持 socket.io 等流的服务器和前端的客户端。
  • @jimmysumshugar 不,我的 API 已经连续发送数据,所以不需要 websocket。我只需要使用 curl 拨打电话并填写文本框

标签: javascript java html api curl


【解决方案1】:

您可以通过发出GET 请求来更新值,并让函数在某个指定的时间间隔内重复。此外,按钮上的onclick 已经添加了一个事件监听器,因此代码会变成这样。

<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>

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

【讨论】:

  • 我用这个 url (jsonplaceholder.typicode.com) 尝试了你的代码,但是当我按下按钮时没有任何反应,你能看看吗?
  • 为方便起见,我已对其进行了编辑并添加了一个 sn-p。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 2021-12-13
  • 2022-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多