복붙노트

[JQUERY] JQuery와 아약스 요청의 진행을 얻을 수있는 가장 깨끗한 방법은 무엇입니까?

JQUERY

JQuery와 아약스 요청의 진행을 얻을 수있는 가장 깨끗한 방법은 무엇입니까?

해결법


  1. 1.$ 아약스 (HTML5 만하지만)에 대한 이런 식으로 뭔가 :

    $ 아약스 (HTML5 만하지만)에 대한 이런 식으로 뭔가 :

    $.ajax({
        xhr: function() {
            var xhr = new window.XMLHttpRequest();
            xhr.upload.addEventListener("progress", function(evt) {
                if (evt.lengthComputable) {
                    var percentComplete = evt.loaded / evt.total;
                    //Do something with upload progress here
                }
           }, false);
    
           xhr.addEventListener("progress", function(evt) {
               if (evt.lengthComputable) {
                   var percentComplete = evt.loaded / evt.total;
                   //Do something with download progress
               }
           }, false);
    
           return xhr;
        },
        type: 'POST',
        url: "/",
        data: {},
        success: function(data){
            //Do something on success
        }
    });
    

  2. 2.그것은이 기술을 사용하고 옵션 매개 변수에 이벤트 논리를 이동하지하는 것이 좋습니다 그래서 jQuery를 이미 약속을 구현했습니다. 나는 진행 약속을 추가하고 지금은 단지 다른 약속으로 사용하기가 쉬운 jQuery 플러그인을했다 :

    그것은이 기술을 사용하고 옵션 매개 변수에 이벤트 논리를 이동하지하는 것이 좋습니다 그래서 jQuery를 이미 약속을 구현했습니다. 나는 진행 약속을 추가하고 지금은 단지 다른 약속으로 사용하기가 쉬운 jQuery 플러그인을했다 :

    $.ajax(url)
      .progress(function(){
        /* do some actions */
      })
      .progressUpload(function(){
        /* do something on uploading */
      });
    

    github에 그것을 확인


  3. 3.나는 아약스 개체의 건설을 차단하는 세 가지 방법에 대해 시도 :

    나는 아약스 개체의 건설을 차단하는 세 가지 방법에 대해 시도 :

    내가 나중에 쉽게 찾을 수 있도록 나는 실제로 내 promise.progress 기능 xhrProgress를 호출합니다. 당신은 당신의 업로드 및 다운로드 청취자를 분리하는 뭔가 다른 이름을 할 수 있습니다. 나는 이것이 원래의 포스터는 이미 그가 필요한 것을 가지고 경우에도 사람을 도움이되기를 바랍니다.

    (function extend_jQuery_ajax_with_progress( window, jQuery, undefined )
    {
    var $originalAjax = jQuery.ajax;
    jQuery.ajax = function( url, options )
    {
        if( typeof( url ) === 'object' )
        {options = url;url = undefined;}
        options = options || {};
    
        // Instantiate our own.
        var xmlHttpReq = $.ajaxSettings.xhr();
        // Make it use our own.
        options.xhr = function()
        {return( xmlHttpReq );};
    
        var $newDeferred = $.Deferred();
        var $oldPromise = $originalAjax( url, options )
        .done( function done_wrapper( response, text_status, jqXHR )
        {return( $newDeferred.resolveWith( this, arguments ));})
        .fail( function fail_wrapper( jqXHR, text_status, error )
        {return( $newDeferred.rejectWith( this, arguments ));})
        .progress( function progress_wrapper()
        {
            window.console.warn( "Whoa, jQuery started actually using deferred progress to report Ajax progress!" );
            return( $newDeferred.notifyWith( this, arguments ));
        });
    
        var $newPromise = $newDeferred.promise();
        // Extend our own.
        $newPromise.progress = function( handler )
        {
            xmlHttpReq.addEventListener( 'progress', function download_progress( evt )
            {
                //window.console.debug( "download_progress", evt );
                handler.apply( this, [evt]);
            }, false );
            xmlHttpReq.upload.addEventListener( 'progress', function upload_progress( evt )
            {
                //window.console.debug( "upload_progress", evt );
                handler.apply( this, [evt]);
            }, false );
            return( this );
        };
        return( $newPromise );
    };
    })( window, jQuery );
    

  4. 4.jQuery를 당신은 물론 당신이 찾고있는 진행을 할 XHR 객체에 액세스 할 수 있도록 모든 아약스 통화 beforeSend으로 완벽한 글로벌 아약스 핸들러를 등록 할 수있는 AjaxSetup () 함수를 가지고

    jQuery를 당신은 물론 당신이 찾고있는 진행을 할 XHR 객체에 액세스 할 수 있도록 모든 아약스 통화 beforeSend으로 완벽한 글로벌 아약스 핸들러를 등록 할 수있는 AjaxSetup () 함수를 가지고


  5. 5.http://www.htmlgoodies.com/beyond/php/show-progress-report-for-long-running-php-scripts.html

    http://www.htmlgoodies.com/beyond/php/show-progress-report-for-long-running-php-scripts.html

    나는 비슷한 솔루션을 찾고 전체이 하나 개의 사용을 발견했다.

    var es;
    
    function startTask() {
        es = new EventSource('yourphpfile.php');
    
    //a message is received
    es.addEventListener('message', function(e) {
        var result = JSON.parse( e.data );
    
        console.log(result.message);       
    
        if(e.lastEventId == 'CLOSE') {
            console.log('closed');
            es.close();
            var pBar = document.getElementById('progressor');
            pBar.value = pBar.max; //max out the progress bar
        }
        else {
    
            console.log(response); //your progress bar action
        }
    });
    
    es.addEventListener('error', function(e) {
        console.log('error');
        es.close();
    });
    

    }

    및 서버 출력

    header('Content-Type: text/event-stream');
    // recommended to prevent caching of event data.
    header('Cache-Control: no-cache'); 
    
    function send_message($id, $message, $progress) {
        $d = array('message' => $message , 'progress' => $progress); //prepare json
    
        echo "id: $id" . PHP_EOL;
        echo "data: " . json_encode($d) . PHP_EOL;
        echo PHP_EOL;
    
       ob_flush();
       flush();
    }
    
    
    //LONG RUNNING TASK
     for($i = 1; $i <= 10; $i++) {
        send_message($i, 'on iteration ' . $i . ' of 10' , $i*10); 
    
        sleep(1);
     }
    
    send_message('CLOSE', 'Process complete');
    

  6. 6.Ajax 요청의 진행을 표시하는 단계를 수행하십시오 :

    Ajax 요청의 진행을 표시하는 단계를 수행하십시오 :

    쉽게 내가 동적으로 표시하고이를 위해 스피너를 숨기기 위해 JS 클래스를 사용을 권장합니다 확인하십시오.

    이게 도움이 되길 바란다!

  7. from https://stackoverflow.com/questions/19126994/what-is-the-cleanest-way-to-get-the-progress-of-jquery-ajax-request by cc-by-sa and MIT license