How to continuously populate HTML textbox from curl API

生来就可爱ヽ(ⅴ<●) 提交于 2021-01-29 06:40:52

问题


I have a HTML textbox which I would like to populate with data received from an API call using curl command. The curl API that I'm using, continuously returns/livestreams data in the following format:

curl <api_endpoint>

data: value1
data: value2
data: value3

And I would like for livestream be displayed in the HTML textbox when a button is clicked. My HTML, JS looks like this:

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

How can I fill the textbox with data stream from a curl <api_endpont> command? There is no need for a websocket, API that I'm using already streams/sends the data continuously in realtime, I just need to make a call and fill the textbox.


回答1:


You can just update the value by making a GET request, and make the function repeat itself at some specified interval. Also onclick on button already adds an event listener, thus the code would go something like this.

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

Edit: To pass event you should pass the keyword event in onclick function call.



来源:https://stackoverflow.com/questions/65327070/how-to-continuously-populate-html-textbox-from-curl-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!