让前端与后端异步起来

有时,后台处理批量数据,需要一定的时间,如果处理一部分往前台送一部分,用户体验要好一些,这样就用到这个知识点了。

后台代码中下:

[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),或脑补一下效果。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值