首页  >  问答  >  正文

支持jQuery的Transfer-Encoding:chunked

我是一名网络开发人员。 在我的脚本中使用 header() 设置“Transfer-Encoding:chunked”。并flush()到网页。 它将在网页中分时打印。 工作正常。 但是,当我使用 jQuery.ajax() 请求 this.it 时,它总是一起输出(分块无用)。

如何解决这个问题?在 jQuery ajax 中使用分块编码?

P粉566048790P粉566048790329 天前617

全部回复(1)我来回复

  • P粉366946380

    P粉3669463802023-10-26 11:10:35

    您不能使用 jquery.ajax 连续读取分块的 http 响应。 jquery ajax仅在连接终止时才会调用成功回调函数。你应该使用 jquery 插件。

    如果您使用 php,则可以使用以下代码:

    <html>
            <head>
                <script src="jquery-1.4.4.js"></script>
                <script src="jquery.stream-1.2.js"></script>
                <script>
    
                    var println = function(string){
                        $("#console").append(string+"<br />");
                    }
    
                    $(document).ready(function(){
    
    
    
                        $.stream("stream.php",{
                            open:function(){
                                println("opened");
                            },
                            message:function(event){
                                println(event.data);
                            },
                            error:function(){
                                println("error");
                            },
                            close:function(){
                                println("closed");
                            }
                        });
    
    
    
                    });
                </script>
            </head>
            <body>
    
    
                <div id="console"></div>
    
            </body>
        </html>

    在服务器端:

    流.php

    <?php
    
    
       header('Content-Encoding', 'chunked');
       header('Transfer-Encoding', 'chunked');
       header('Content-Type', 'text/html');
       header('Connection', 'keep-alive');
    
       ob_flush();
       flush();
    
       echo("23123454645645646;");
    
    
       $p = "";
       for ($i=0; $i < 1024; $i++) { 
           $p .= " ";
       };
       echo($p.";");
    
    
    
       for ($i = 0; $i < 10000; $i++) {
          echo('6;string;');
          ob_flush();
          flush();
          sleep(2);
       }
    
    
    
    
    ?>

    回复
    0
  • 取消回复