【问题标题】:ajax xhr lengthComputable return false with php fileajax xhr lengthComputable 使用 php 文件返回 false
【发布时间】:2013-04-08 16:43:19
【问题描述】:

我正在使用 XMLHttpRequest 执行 ajax 请求,以显示请求的进度。它适用于 html 文件,但 evt.lengthComputable 使用 php 文件返回 false。

我的 php 文件以 utf-8 编码,没有任何特殊内容。

                xhr: function()
            {

              console.log('xhr');
              var xhr = new XMLHttpRequest();


              xhr.addEventListener('loadend', uploadComplete, false);
              function uploadComplete(event) {
                  console.log('uploadComplete');
                  //do stuff
              }


              //Download progress
              xhr.addEventListener("progress", function(evt){
                console.log([evt.lengthComputable, evt.loaded, evt.total]);
                if (evt.lengthComputable) {
                  var percentComplete = (evt.loaded / evt.total) * 100;


                }
              }, false);
              return xhr;
            }

感谢您的帮助:)!

【问题讨论】:

    标签: php xmlhttprequest


    【解决方案1】:

    由于php文件是动态的,需要设置正确的Content-Length头:

    <?
    ob_start();
    /* your code here */
    
    $length = ob_get_length();
    header('Content-Length: '.$length."\r\n");
    header('Accept-Ranges: bytes'."\r\n");
    ob_end_flush(); 
    

    【讨论】:

    • 始终在 php 脚本末尾使用这些行来正确确定长度并输出 html 和数据(如果有) $length = ob_get_length(); header('Content-Length: '.$length."\r\n"); header('接受范围:字节'。"\r\n"); ob_end_flush();
    猜你喜欢
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-25
    相关资源
    最近更新 更多