7

i'm a web developer. in my script use header() to set "Transfer-Encoding:chunked". and flush() to webpage. it will print in webpage time-shared. it works ok. but, when i use jQuery.ajax() to request this.it always output all together(chunked unuseful).

how to solute this? use chunked encoding in jQuery ajax?

Mikhail
  • 9,186
  • 4
  • 33
  • 49
Zaric Zhang
  • 99
  • 1
  • 7

1 Answers1

12

you cannot use jquery.ajax to read chunked http response continuously. jquery ajax will call the success callback function only when connection terminates. You should use this jquery plugin.

if you are using php then you can use this 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>

in 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);
   }




?>
Partha Pal
  • 300
  • 1
  • 5
  • 4
    The `jquery.stream` project is moved to github and renamed to Portal but Portal reached end-of-life and absorbed into Vibe but Vibe is renamed to Cettia. Go to http://cettia.io – Stephan May 13 '15 at 13:10
  • 1
    @Stephan, can you please maintain the library please? only few people understand the importance of this library. Can we please put it in github.com and make it frozen so that nobody can in 10 years keep changing its name and confuse the community? –  Aug 04 '16 at 22:07
  • 2
    @YumYumYum Cettia has already a maintainer. Here is his Github profile: https://github.com/flowersinthesand – Stephan Aug 05 '16 at 12:04