当需要操作的数据量过大,需要切片处理
场景:文件上传,处理数据量大,php处理超时,前端等待时间过长
// 新建data.php
<?php
$page = $_POST['page'] ?? 1;
$size= $_POST['size'] ?? 100;

$totalNum = 500;
$list = "";

for($i= ($page-1) * $size; $i < $page * $size; $i++){
    $list .= $i .", "; 
}
$list = $list ."<hr />";

$status = false;

if( $page*$size <= $totalNum ){
    $status = true;
}
$page = $page + 1;
sleep(1);
// echo "<pre>";
// print_r($list);
// echo "</pre>";exit;

$res = [
    'status'=> $status,
    'page'  => $page,
    'list'  => $list,
];
echo json_encode($res);
前端递归调用,后端给跳出条件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h2>数据切片操作</h2>
    <button id="btn">开始执行</button>
    <p class="progress"></p>
    <script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
    <script>
    function getData($page=1){
        $.post("./data.php",{
            page: $page,
            size:100,
        },
        function(data){
            data = eval("("+data+")");
            if(data.status){
                // console.log( data.page );
                // console.log( data.list );
                $(".progress").append(data.list);
                getData(data.page);
            }else{
                $(".progress").append("\n"+"done");
            }
        });
    }
    $( "#btn" ).on( "click", function() {
        // console.log( $( this ).text() );
        $(".progress").text("Data: ")
        getData()
    });
        
    </script>
</body>

</html>

效果如图


iwiilbeback
41 声望1 粉丝