I'm sending data from my textbox to a server endpoint and then displaying the data which server streams back in the textbox. After the server is done streaming and the textbox is completely updated, I need to store the value of the textbox to perform further operations on the data. I'm using this sse.js library to POST the data to the server.
<button type="button" onclick="post()">get</button>
<script type="text/javascript" src="sse.js"></script>
<script>
url = "API-ENDPOINT";
let textArea = document.getElementById("value");
function post(callback){
//GET TEXTBOX VALUE TO SEND TO THE SERVER
var v = String(textArea.value);
console.log(v);
var source = new SSE(url, {
method: 'POST',
headers: { 'Content-Type': 'text/plain' },
payload: v //SPECIFY TEXTBOX VALUE TO SEND TO THE SERVER
});
var arr = [];
source.addEventListener('message', function (e) {
arr.push(e.data); //ADD THE DATA FROM THE SERVER-STREAM TO AN ARRAY, TO PRINT THE WHOLE MESSAGE
textArea.value = arr.map(el => el || " ").join(''); //FORMAT AND DISPLAY ARRAY IN THE TEXTBOX
});
source.stream();
}
The code above gets the textbox's value, sends it to a server, and populates the textbox with server response. Now I would like to get the textbox's value after it has finished updating. But the problem is: my server endpoint uses SSE to continuosly stream the data, which means that there is no single chunk of data which will be received, but rather many pieces of data will received continously (that's why created the arr
array to append the pieces and display the whole data.) The data which server sends is sentences, and it sends them one-word-at-a-time. So, when you press the get
button, textbox gets dynamically populated with increasing amount of text. When the textbox is done updating, I need to store the textbox value to perform further operations on text, like clipping the last 5 charactes for example.
function clip(){
s = textArea.value;
s = s.slice(0, -5);
textArea.value = s;
console.log('clipped');
}
I tried using callback()
to in the message
`EventHandler, but that didn't work, since EventHandler receives one word at a time, and placing the callback there clipped parts from each word instead of the end of finished output:
<button type="button" onclick="post(clip)">get</button>
source.addEventListener('message', function (e) {
arr.push(e.data);
textArea.value = arr.map(el => el || " ").join('');
callback();
});
Placing callback()
at the end of the post()
didn't work either and it clipped the textbox value before stream even began:
source.stream();
callback();
Does anybody know how to get the textbox value and perform operations on it after the post()
function has completed updating the textbox?
question from:
https://stackoverflow.com/questions/65904113/get-textbox-value-after-the-sse-stream 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…