有时,后台处理批量数据,需要一定的时间,如果处理一部分往前台送一部分,用户体验要好一些,这样就用到这个知识点了。
后台代码中下:
[HttpGet("/getents")]public async IAsyncEnumerable<Entity> GetEntitys(){ for (var i = 0; i < 20; i++){_logger.LogInformation(i.ToString());await Task.Delay(RandomNumberGenerator.GetInt32(100, 500));yield return new Entity { ID = i, Time = DateTime.Now };}}
前端代码,从后台取到数据后,展现在前端(我这里是拼接,用vue也可以),因为数据没有取完,所以不是一个完整的json字符串,需要在最后加上“]”
@{ViewData["Title"] = "Home Page";
}
<div class="text-center"><h1 class="display-4">实时加载</h1><div id="divmessage" class="alert alert-warning" role="alert"><span id="message"></span></div><ul id="data" class="list-group"></ul>
</div>
@section Scripts{
<script>$(function() {var xhr=new $.ajaxSettings.xhr(); xhr.onreadystatechange=function(){if(xhr.readyState==3){var list=JSON.parse(xhr.responseText.replace(']','')+']');$("#message").html("加载中…… 【"+list.length+"】")var html=""$(list).each(function(index,item){html+='<li class="list-group-item">'+item.id+" "+item.time+"</li>"})$("#data").html(html)}else if(xhr.readyState==4){var list=JSON.parse(xhr.responseText.replace(']','')+']');$("#message").html("加载完成,共"+list.length+"条记录")$("#divmessage").removeClass("alert-warning")$("#divmessage").addClass("alert-success")}}xhr.open('GET', '/getents')xhr.send()});
</script>
}
效果是后台处理一块,就返回一块,前台展示一块,因为这里不能放视频和动图,所以可以自行运行结果看一下(.net6),或脑补一下效果。