Я не могу обновить индикатор выполнения через $ .ajax при отправке формы - PullRequest
0 голосов
/ 24 декабря 2010

После отправки формы появляется индикатор выполнения и вызывается функция getProgress.getProgress проверяет php-файл (который использует мод apache uploadprogress для получения текущего прогресса загрузки) и возвращает число от 0 до 100 (что означает завершение).

OK, идея в том, что getProgressвыполняется автоматически, если возвращаемое число не равно 100. В противном случае форма продолжает загружать .php, где файл обрабатывается.

ЭТО ТО, ЧТО ИЩЕТ IM: http://screenr.com/ByG <-video. </p>

Вот часть HTML.

<form method="post" action="upload.php" enctype="multipart/form-data" id="UploadForm">
    <input type="hidden" id="uid" name="UPLOAD_IDENTIFIER" value="<?php echo $uid; ?>">
    <input type="file" name="file">
    <input type="submit" name="submit" value="Upload!">
</form>
<div id="UploadBarContainer">
        <div id="LoadBar"></div>
        <div id="ProgressBar"></div>
    </div>

Вот часть jQuery. Который, похоже, не работает

$(function(){

    // This flag determines if the upload has started
    var started = false;

    // Start progress tracking when the form is submitted
    $('#UploadForm').submit(function() {

        //Update the flag to true.
        started = true;

        //Hide the form.
        $('#UploadForm').hide();

        //Show the progress bar.
        $('#UploadBarContainer, #LoadBar, #ProgressBar').show();

        //Start updating progress after a 2 second delay.
        //This is to prevent the getprogress.php assume that upload is complete. 
        setTimeout(function () {

            // We pass the upload identifier to our function
            getProgress($('#uid').val());

        }, 2000);

    });


    //Function used to get the current upload progress.
    //It should be executed over and over again untill the result is 100.
    function getProgress(id) {

        //Get the current time.
        var time = new Date().getTime();

        //Make an ajax request to the server.
        $.ajax({

            //Pass the data trought GET method.
            type: 'GET',

            //Get the progress from this php file.
            url: 'getprogress.php',                         

            //Pass our upload identifier as a parameter and current time to prevent caching.
            data: { uid: id, t: time }, 

            //Get the results.
            success: function (data) {

                //Get the output as an integer.
                var progress = parseInt(data, 10);

                //If upload progress is not 100, change bar percentage and update again.
                if (progress < 100) {

                    //Update the progress bar percentage.
                    //But only if we have started.
                    $('#ProgressBar').css('width', progress + '%');

                    //If we aren't done, update again.
                    getProgress(id);

                }
            }

        });

    }

});

На всякий случай это помогает, вот файл getprogress.php, вызываемый по запросу $ .ajax.

if (isset($_GET['uid'])) {
    // Fetch the upload progress data
    $status = uploadprogress_get_info($_GET['uid']);
    if ($status) {
        // Calculate the current percentage
        echo round($status['bytes_uploaded']/$status['bytes_total']*100);
    }
    else {
        // If there is no data, assume it's done
        echo 100;
    }
}

Любая помощь приветствуется, у меня есть живое демо, но я боюсь, что вы можете загрузить.

Ответы [ 2 ]

0 голосов
/ 31 декабря 2010

Ну, наконец, я пришел к выводу, что это невозможно сделать в браузерах webkit, таких как Opera, Chrome и Safari, но не так в Firefox и Internet Explorer.

Браузеры Webkit обычно блокируют любой ajax во время загрузки файла.

Вы можете проверить это: https://bugs.webkit.org/show_bug.cgi?id=23933

0 голосов
/ 25 декабря 2010

только новые версии некоторых браузеров поддерживают процесс загрузки файлов. Вы должны проверить свою сеть с помощью firebug, если getprogress.php отправляет числа или просто ошибки. Вы можете посмотреть это: Http:

...