如何在一页上获取JS变量值并传递回PHP中的另一页

时间:2019-03-26 21:03:25

标签: javascript php

我目前有两个用php编码的页面,一个页面称为upload.php,另一页面称为processing.php。

在processing.php中,我目前运行了一些Javascript,目的是检查日志文件中的视频编码进度,以获取剩余的百分比。此变量称为“ progress”(当在processing.php上使用console.log时,此方法工作正常,我可以看到递增百分比),我需要能够将此值返回到我的upload.php页面,以便我可以动态地用当前值更新进度条。

我已经完成了拼图的一部分,那就是显示文件上传的进度条。

我已经在我的upload.php中包含了一些JS代码,并在processing.php页面中使用了JS代码。

我尝试做的一件事是将JS变量插入到processing.php页面上的PHP会话变量中,然后在upload.php上回显此会话变量。

我在尝试使用会话的代码段中包括了以下内容。

Upload.php

<?php session_start();?>
<?php 
$formProvider = new VideoDetailsFormProvider($con);
echo $formProvider->createUploadForm();
?>
</div>

<script>



$("form").submit(function() {
  $("#loadingModal").modal("show");    

  var $el = $("#loadingModal");

     $form = $(this);


     uploadVideo($form, $el);
});

function uploadVideo($form, $el){
  var formdata = new FormData($form[0]); //formelement

  var ajax= new XMLHttpRequest();

  ajax.upload.addEventListener("progress", function(event){
    var percent = Math.round(event.loaded /event.total) * 100;

    $el.find('#progressBarUpload').width(percent+'%').html(percent+'%');




    //console.log(percent);
  });

  //progress completed load event

  ajax.addEventListener("load", function(event){
    $el.find('#progressBarUpload').addClass('progress-bar bg-success').html('Upload completed...');


  });

  ajax.addEventListener("error", function(event){
    $el.find('#status').innerhtml = "Upload Failed";


  });

  ajax.addEventListener("abort", function(event){
    $el.find('#status').innerhtml = "Upload Aborted";

  });

  ajax.open("POST", "processing.php");
  ajax.send(formdata);

}


 Please wait. This might take a while.
           <?php echo($_SESSION['convertProgress']);?>
        <div class="progress">
          <div id="progressBarUpload" class="progress-bar" role="progressbar" style="width: 0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
        </div>

Processing.php


<?php session_start();
$convertProgressTest = $_SESSION['convertProgress'];
?>
<script>
    var _progress = function(i){
        i++;
        // THIS MUST BE THE PATH OF THE .txt FILE SPECIFIED IN [1] :
        var logfile = 'uploads/videos/logs/output.txt';

        /* (example requires dojo) */

        $.post(logfile).then( function(content){
// AJAX success
                var duration = 0, time = 0, progress = 0;
                var resArr = [];

                // get duration of source
                var matches = (content) ? content.match(/Duration: (.*?), start:/) : [];
                if( matches.length>0 ){
                    var rawDuration = matches[1];
                    // convert rawDuration from 00:00:00.00 to seconds.
                    var ar = rawDuration.split(":").reverse();
                    duration = parseFloat(ar[0]);
                    if (ar[1]) duration += parseInt(ar[1]) * 60;
                    if (ar[2]) duration += parseInt(ar[2]) * 60 * 60;

                    // get the time
                    matches = content.match(/time=(.*?) bitrate/g);
                    console.log( matches );

                    if( matches.length>0 ){
                        var rawTime = matches.pop();
                        // needed if there is more than one match
                        if ($.isArray(rawTime)){
                            rawTime = rawTime.pop().replace('time=','').replace(' bitrate','');
                        } else {
                            rawTime = rawTime.replace('time=','').replace(' bitrate','');
                        }

                        // convert rawTime from 00:00:00.00 to seconds.
                        ar = rawTime.split(":").reverse();
                        time = parseFloat(ar[0]);
                        if (ar[1]) time += parseInt(ar[1]) * 60;
                        if (ar[2]) time += parseInt(ar[2]) * 60 * 60;

                        //calculate the progress
                        progress = Math.round((time/duration) * 100);
                    }

                    resArr['status'] = 200;
                    resArr['duration'] = duration;
                    resArr['current']  = time;
                    resArr['progress'] = progress;

                    console.log(resArr);

                    /* UPDATE YOUR PROGRESSBAR HERE with above values ... */
                  /*  $("#progressBarconvert").width(progress+'%').html(progress+'%');
                    if(progress==100){
                        $("#progressBarconvert").addClass('progress-bar bg-success').html('Conversion Completed...');
                    }*/
                        var convertProgress = progress;

                    if(progress==0 && i>20){
                        //TODO err - giving up after 8 sec. no progress - handle progress errors here
                        console.log('{"status":-400, "error":"there is no progress while we tried to encode the video" }');
                        return;
                    } else if(progress<100){

                        setTimeout(function(){ _progress(i); }, 400);
                    }
                } else if( content.indexOf('Permission denied') > -1) {
                    // TODO - err - ffmpeg is not executable ...
                    console.log('{"status":-400, "error":"ffmpeg : Permission denied, either for ffmpeg or upload location ..." }');
                }
            },
            function(err){
// AJAX error
                if(i<20){
                    // retry
                    setTimeout(function(){ _progress(0); }, 400);
                } else {
                    console.log('{"status":-400, "error":"there is no progress while we tried to encode the video" }');
                    console.log( err );
                }
                return;
            });

    }
    setTimeout(function(){ _progress(0); }, 800);
</script>


2 个答案:

答案 0 :(得分:0)

由于您不想离开upload.php,因此必须在return false;之后添加uploadVideo($form, $el);

否则,您异步触发上传并同步进入progress.php(这意味着您退出了upload.php)


您在这里有3个职责,因此可以通过3个文件来完成:

upload.php -显示上传表单

convert.php -进行转换

progress.php -获取进度

在您的convert.php中,您将需要添加行$_SESSION['convertProgress'] = convertProgress;

在您的upload.php中,您现在可以通过以下方式更新进度条:

$.ajax('progress.php', function(content) {
    // set element value etc...
});

一旦开始上传,文件就会被convert.php异步上传并转换。现在,您可以触发一个JS-Timer,它反复执行上述对progress.php的调用,直到达到100。

如果您希望能够进行一些错误处理,则可以使用JSON将更多数据传递回调用progress.php的upload.php。

PHP(示例):

json_encode([
    'progress' => 0,
    'message' => '',
]);

JS解码:

JSON.parse(<content of progress.php>)

答案 1 :(得分:0)

我现在已经设法解决了这个问题,虽然它不是很漂亮,并且可能不是最好的方法,但是它对我有用,使用@Pilan建议并帮助我解决此问题。

共有3页

Update.php页面,Processing.php页面和convertProgress.php页面,convertProgress.php页面包含在我的文章开头提到的Javascript代码。 upload.php包含以下内容。


 var testing;

    function beginUpload() {


        $.ajax({
            url: 'convertProgress.php',
            type: 'POST',
            //async: false,
            data: {},
            success: function (response) { //we got the response
                if(response.progress){
                    testing = response.progress
                    console.log(testing);
                }else {
                    beginUpload();
                    getProgress();
                }
            //var testing =  response.progress;

            },
            error: function (jqxhr, status, exception) {
                alert('Exception:', exception);
            }
        });

        //console.log(testing);


    }

Upload.php也具有与convertProgress.php相同的javascript代码


<script>
    function getProgress() {
        var _progress = function (i) {
            i++;
            // THIS MUST BE THE PATH OF THE .txt FILE SPECIFIED IN [1] :
            var logfile = 'uploads/videos/logs/output.txt';

            /* (example requires dojo) */

            $.post(logfile).then(function (content) {
// AJAX success
                    var duration = 0, time = 0, progress = 0;
                    var resArr = [];

                    // get duration of source
                    var matches = (content) ? content.match(/Duration: (.*?), start:/) : [];
                    if (matches.length > 0) {
                        var rawDuration = matches[1];
                        // convert rawDuration from 00:00:00.00 to seconds.
                        var ar = rawDuration.split(":").reverse();
                        duration = parseFloat(ar[0]);
                        if (ar[1]) duration += parseInt(ar[1]) * 60;
                        if (ar[2]) duration += parseInt(ar[2]) * 60 * 60;

                        // get the time
                        matches = content.match(/time=(.*?) bitrate/g);
                        console.log(matches);

                        if (matches.length > 0) {
                            var rawTime = matches.pop();
                            // needed if there is more than one match
                            if ($.isArray(rawTime)) {
                                rawTime = rawTime.pop().replace('time=', '').replace(' bitrate', '');
                            } else {
                                rawTime = rawTime.replace('time=', '').replace(' bitrate', '');
                            }

                            // convert rawTime from 00:00:00.00 to seconds.
                            ar = rawTime.split(":").reverse();
                            time = parseFloat(ar[0]);
                            if (ar[1]) time += parseInt(ar[1]) * 60;
                            if (ar[2]) time += parseInt(ar[2]) * 60 * 60;

                            //calculate the progress
                            progress = Math.round((time / duration) * 100);
                        }

                        resArr['status'] = 200;
                        resArr['duration'] = duration;
                        resArr['current'] = time;
                        resArr['progress'] = progress;

                        console.log(resArr);

                        /* UPDATE YOUR PROGRESSBAR HERE with above values ... */
                         $("#progressBarconvert").width(progress+'%').html(progress+'%');
                          if(progress==100){
                              $("#progressBarconvert").addClass('progress-bar bg-success').html('Conversion Completed...');
                          }


                        if (progress == 0 && i > 20) {
                            //TODO err - giving up after 8 sec. no progress - handle progress errors here
                            console.log('{"status":-400, "error":"there is no progress while we tried to encode the video" }');
                            return;
                        } else if (progress < 100) {

                            setTimeout(function () {
                                _progress(i);
                            }, 400);
                        }
                    } else if (content.indexOf('Permission denied') > -1) {
                        // TODO - err - ffmpeg is not executable ...
                        console.log('{"status":-400, "error":"ffmpeg : Permission denied, either for ffmpeg or upload location ..." }');
                    }
                },
                function (err) {
// AJAX error
                    if (i < 20) {
                        // retry
                        setTimeout(function () {
                            _progress(0);
                        }, 400);
                    } else {
                        console.log('{"status":-400, "error":"there is no progress while we tried to encode the video" }');
                        console.log(err);
                    }
                    return;
                });

        }
        setTimeout(function () {
            _progress(0);
        }, 800);
    }
</script>

虽然不漂亮,但对我有用。希望这对希望从FFMPEG获取转换进度并填充引导进度栏的人有所帮助