JQuery ajax xhr在开始之前100%完成了吗?

时间:2016-10-12 10:57:18

标签: javascript php jquery ajax xmlhttprequest

我有很长的脚本,可能需要几分钟才能执行,因此我决定创建一个将返回当前状态的进度条。

但我有问题因为xhr evt.loaded / evt.total(30/30)在开始执行长脚本之前返回1(100%)...

$(".systemform").live("submit",function(e) {    //run system
    run_system(); //start run system
    e.preventDefault(); 
}); 

function run_system(){
    $("#leftcontainer").html("");
    $("#leftcontainer").show();           
    $("#chartContainer").hide();

    $(".loading").show();

    var sysid = $(".sysid:checked").val();
    var oddstype = $(".odds_pref").val();
    var bettypeodds = $(".bet_type_odds").val();
    var bookie = $(".bookie_pref").val();
    if (typeof oddstype === "undefined") {
        var oddstype = $(".odds_pref_run").val();
        var bettypeodds = $(".bet_type_odds_run").val();
        var bookie = $(".bookie_pref_run").val();                   
    }

    $.ajax({                
        xhr: function () {
            var xhr = new window.XMLHttpRequest();
            xhr.upload.addEventListener("progress", function (evt) {
                if (evt.lengthComputable) {
                    var percentComplete = evt.loaded / evt.total;
                    console.log(percentComplete);
                    $('.progress').css({
                        width: percentComplete * 100 + '%'
                    });
                    if (percentComplete === 1) {
                        $('.progress').addClass('hide');
                    }
                }
            }, false);
            xhr.addEventListener("progress", function (evt) {
                if (evt.lengthComputable) {
                    var percentComplete = evt.loaded / evt.total;
                    console.log(percentComplete);
                    $('.progress').css({
                        width: percentComplete * 100 + '%'
                    });
                }
            }, false);
            return xhr;
        },
        type: "POST",
        url: '/index.php?/system/system_options/left/'+'1X2/'+oddstype+'/'+bettypeodds+'/'+bookie,          
        data: {             
            system : sysid,
            showpublicbet : showpublicbet 
        }, // serializes the form's elements.       
        dataType:"json",
        success: function(data)
        {     
            console.log(data);                                     
            $("#systemlist").load('/index.php?/system/refresh_system/'+sysid,function(e){
                systemradiotocheck(); 
            });
            $("#resultcontainer").load('/index.php?/system/showresults/'+sysid+'/false');                                                                             
            $("#resultcontainer").show();
            $("#leftcontainer").html(data.historic_table);
            $("#rightcontainer").html(data.upcoming_table); 
            var count = 0;
            var arr = [];
            $("#rightrows > table > tbody > tr").each(function(){
                var row = $(this).data('row');
                if(typeof row !== 'undefined'){
                    var rowarr = JSON.parse(JSON.stringify(row));
                    arr[count] = rowarr;                                    
                    $(this).find('td').each(function(){
                        var cell = $(this).data('cell');
                        if(typeof cell !== 'undefined'){
                            var cellarr = JSON.parse(JSON.stringify(cell));
                            arr[count][6] = cellarr[0];
                        } 
                    });
                    count ++;
                }
            });                           
            if(oddstype == "EU" && bookie == "Bet365"){
                $('.bet365').show();
                $('.pinnacle').hide();
                $('.ukodds').hide();
            }

            if(oddstype == "EU" && bookie == "Pinnacle"){
                $('.pinnacle').show();
                $('.bet365').hide();
                $('.ukodds').hide();
            }           

            if(oddstype == "UK"){
                $('.bet365').hide();
                $('.pinnacle').hide();
                $('.ukodds').show();
            }   

            if(bookie == "Pinnacle"){
                $(".pref-uk").hide();
            }                                                                     
            else{
                $(".pref-uk").show();
            }                             
            $(".loading").hide(); 
            runned = true;
            var options = {
                animationEnabled: true,
                toolTip:{   
                    content: "#{x} {b} {a} {c} {y}"      
                },
                axisX:{
                    title: "Number of Games"
                },
                axisY:{
                    title: "Cumulative Profit"
                },
                data: [
                {
                    name: [],
                    type: "splineArea", //change it to line, area, column, pie, etc
                    color: "rgba(54,158,173,.7)",
                    dataPoints: []
                }
                ]   
            }; 
                    //console.log(data);
            var profitstr = 0;
            var parsed = $.parseJSON(JSON.stringify(data.export_array.sort(custom_sort)));
            var counter = 0;
            for (var i in parsed) 
            {
                profitstr = profitstr + parsed[i]['Profit'];
                //console.log(profitstr);
                var profit = parseFloat(profitstr.toString().replace(',','.'));
                //console.log(profit);
                var event = parsed[i]['Event'].toString();
                var hgoals = parsed[i]['Home Goals'].toString();
                var agoals = parsed[i]['Away Goals'].toString();
                var result = hgoals + ":" + agoals;
                var date = parsed[i]['Date'].toString();
                var bettype = parsed[i]['Bet Type'];
                var beton = parsed[i]['Bet On'];
                var handicap = parsed[i]['Handicap'];
                counter++;
                options.data[0].dataPoints.push({x: counter,y: profit,a:event,b:date,c:result});
            }

            $("#chartContainer").show();
            $("#chartContainer").CanvasJSChart(options);

            $(".hidden_data").val(JSON.stringify(data.export_array));
            $(".exportsys").removeAttr("disabled");
            $(".exportsys").removeAttr("title");
        },          
        error: function(xhr, textStatus, error){
            console.log(xhr.statusText);
            console.log(textStatus);
            console.log(error);
        }
    }); 
}

这里有什么问题???

当我在console.log(evt)时,我得到了这个: 来自上传进度:

  

ProgressEvent {isTrusted:true,lengthComputable:true,loaded:30,   总数:30,输入:"进度" ...}

来自下载进度:

  

system:302 ProgressEvent {isTrusted:true,lengthComputable:false,   已加载:28987,总计:0,类型:"进度" ...}系统:302 ProgressEvent   {isTrusted:true,lengthComputable:false,loaded:104950,total:0,   键入:"进度" ...}

看起来加载太大了,我的解决方案是什么?

我解决了这个问题直接通过JQuery访问文件而不是php使用$ .get:

function refreshProgress(){
    $.get('1_run.txt', function(data) {
        console.log(data);
    }); 
}

1 个答案:

答案 0 :(得分:0)

ajax xhr函数替换此代码

xhr: function ()
                {
                    var xhr = new window.XMLHttpRequest();
                    //Upload progress
                     $("#loadAdd").show();
                    xhr.upload.addEventListener("progress", function (evt) {
                        if (evt.lengthComputable) {
                            var percentComplete = (evt.loaded / evt.total) * 100;
                            $('#loadAdd .progress-bar').css('width', percentComplete + '%');
                        }
                    }, false);
                    //Download progress
                    xhr.addEventListener("progress", function (evt) {
                        if (evt.lengthComputable) {
                            var percentComplete = evt.loaded / evt.total;
                        }
                    }, false);
                    return xhr;
                }, 

html代码

<div class="col-lg-12">
    <div id="loadAdd" class="progress progress-striped active">
        <div class="progress-bar progress-bar-success"    role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 00%">
        </div>
    </div>
</div>