search

Home  >  Q&A  >  body text

Support jQuery's Transfer-Encoding:chunked

I am a web developer. Using header() in my script sets "Transfer-Encoding:chunked". and flush() to the web page. It will be printed in a time-shared manner in the web page. Works fine. However, when I request this.it using jQuery.ajax(), it is always outputted together (chunking is useless).

how to solve this problem? Using chunked encoding in jQuery ajax?

P粉566048790P粉566048790424 days ago715

reply all(1)I'll reply

  • P粉366946380

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

    You cannot use jquery.ajax to read chunked http responses continuously. jquery ajax only calls the success callback function when the connection is terminated. you should use This jquery plugin.

    If you use php, you can use the following code:

    <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>

    On the server side:

    Stream.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);
       }
    
    
    
    
    ?>

    reply
    0
  • Cancelreply