!-- indexhtml --!DOCTYPE htmlhtmlhead titleiPerf3 Web Interfacetitle script src=httpscodejquerycomjquery-351minjsscript script $documentreadyfunction var output = $#output;
要修正程序以显示iperf3的输出,可以在ajax请求的success函数中添加一个回调函数来处理iperf3的输出。具体做法是将回调函数添加到EventSource的onmessage事件监听器中,这样每当接收到新的iperf3输出时,回调函数就会被调用。
修正后的代码如下:
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>iPerf3 Web Interface</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function() {
var output = $('#output');
$('#start').click(function() {
$.ajax({
url: '/start',
type: 'POST',
success: function(response) {
output.empty();
output.text('Command started.');
var source = new EventSource('/stream');
source.onmessage = function(event) {
output.append(event.data + '\n');
};
}
});
});
$('#stop').click(function() {
$.ajax({
url: '/stop',
type: 'POST',
success: function(response) {
output.text('Command stopped.');
}
});
});
});
</script>
</head>
<body>
<h1>iPerf3 Web Interface</h1>
<button id="start">Start Command</button>
<button id="stop">Stop Command</button>
<pre id="output"></pre>
</body>
</html>
这样,当点击"Start Command"按钮时,会发送一个ajax请求到服务器的/start路径,并在成功响应后,使用EventSource对象建立与服务器的/stream路径的持久连接。每当服务器有新的iperf3输出时,会通过这个持久连接发送给客户端,并触发EventSource对象的onmessage事件,进而调用回调函数将新的iperf3输出追加到页面上的<pre>元素中。
请确保服务器端代码正确实现了/start和/stream的功能,以便与上述前端代码配合运行
原文地址: https://www.cveoy.top/t/topic/iR9C 著作权归作者所有。请勿转载和采集!