同时运行两个ajax调用?

时间:2016-10-11 15:07:04

标签: php jquery ajax

如果我有一个带有foreach循环的ajax调用,我更新了一个文本文件,同时我想读取该文件,并通过另一个第二次调用显示第一次调用中更改的内容,我可以实现吗?

第一次运行时,第二次运行直到第一次运行完毕。

我想同时运行第一个和第二个。在第二个调用中,每隔一秒我想检查第一次调用创建的文件中的状态 - 类似于进度条。

function startTimer(){
    timer = window.setInterval(refreshProgress, 1000);
}

function refreshProgress(){
    $.ajax({                      
        type: "POST",
        url: '/index.php?/system/run_progress_checker',
        dataType:"json",
        success: function(data)
        {   
            console.log(data);
            if (data.percent == 100) {
                window.clearInterval(timer);
                timer = window.setInterval(completed, 1000);
            }
        },
        error: function(xhr, textStatus, error){
            console.log(xhr.statusText);
            console.log(textStatus);
            console.log(error);
        }                        
    });     
}

function completed() {
  //$("#message").html("Completed");
  window.clearInterval(timer);
}   

$(".systemform").submit(function(e) {   //run system
   $.when(startTimer(),run_system()).then(function(){});
   e.preventDefault(); // avoid to execute the actual submit of the form.
}); 


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({                      
        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'];
                     //alert(profitstr);
                     //alert(profit); 
                     //options.data[0].name.push({event});
                     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);
            }
        });         
}

后端部分并不是那么重要,因为它有效。

1 个答案:

答案 0 :(得分:0)

对于jQuery的$。然后$ .then来说,这听起来很棒。在第一部分,$ .when,你将有第一个ajax调用,当它完成时...你可以将数据从第一部分移植到$ .then部分。例如:

 $.when(
      //perform first ajax call and pass this data to the 'then'.
                $.ajax(
                 {
                     type: "POST",
                     url: "<<insert url>>",
                     contentType: "application/json; charest=utf-8",
                     success: function (data) {
                         //process data

                     },
                     error: function (XMLXHttpRequest, textStatus, errorThrown) {

                     }
                 })
            ).then(function (data, textStatus, jqXHR) {


                var obj = $.parseJSON(data); // take data from above and use it to perform second ajax call.
                var params = '{ "CustomerID": "' + obj[0].CustomerID + '" }';
                 $.ajax(
                 {
                     type: "POST",
                     url: "<<insert url>>",
                     data:  params,
                     contentType: "application/json; charest=utf-8",
                     success: function (data) {
                         //process data

                     },
                     error: function (XMLXHttpRequest, textStatus, errorThrown) {

                     }
                 })

            });

        }
    });