开发者

jquery foreEach with ajax / keep order

i have problem with jquery $.ajax and forEach on an array...

here's the code

function getFfttData() {
 // reinit object
 pdatas={};
 checked_m开发者_运维百科atchs=0;
 var licence_arr=[];
 $('#calculator_form input[name="licence"]').each(function() {
  var value = $(this).val().trim();
  if  (value != '' ) {
   licence_arr.push(value);
  }
 });
 if (licence_arr.length === 0 ) {
  show_error("Aucune licence à vérifier....");
  return;
 }
 var coef = parseFloat($('#type_compet').attr("value"));
 if (coef === 0) {
  show_error("Choisissez le type de compétition pour vos matchs");
  return;
 }
 pdatas.coef=coef;
 pdatas.compet_id = $('#type_compet :selected').attr("name");
 pdatas.compet_name = $('#type_compet :selected').text();
 pdatas.pts_officiels = parseInt($("#points_fftt").html().trim(), 10);
 pdatas.pts_mensuels = parseInt($("#pts_off_mensuels").html().trim(), 10);

 pdatas.licence_arr=licence_arr;
 pdatas.adv_name=[];
 pdatas.adv_club=[];
 pdatas.adv_cat=[];
 pdatas.pts_adv_encours=[];
 pdatas.pts_adv_mensuels=[];
 pdatas.matchs_rejetes=[];
 pdatas.matchs_count=licence_arr.length;
 $("#loader").show();
 pdatas.licence_arr.forEach(function(licence) { 
  dcheck=false;
  return getPlayerDatas(licence);
 });
 $("#loader").hide();
}

function getPlayerDatas(licence) {
 if (dcheck === false) { // check categorie Masculin
  var req='http://fftt.com/sportif/pclassement/php3/FFTTfi.php3?session=precision='+licence+'&reqid=200';
 } else { //feminine
  var req='http://fftt.com/sportif/pclassement/php3/FFTTfi.php3?session=precision='+licence+'&reqid=300';
 }

 $.ajax({
  type: "GET",
  url: req,
  timeout : 5000,
  success: function(data) {
   data.licence=licence;
   var ret_licence = $(data.responseText).find('td').eq(3).text().trim().replace(/\s+/g," ");
   var pts_mensuels = $(data.responseText).find('td').eq(21).text().trim().replace(/\s+/g," ");
   if (ret_licence != licence) {
    if (dcheck === false) {
     dcheck = true;
     return getPlayerDatas(licence);
    }
   } 
   dcheck=false;
   return store_player_datas(data);
  }
 });
}


function store_player_datas(data) {
 var error = $(data.responseText).find('strong').eq(0).text().trim();
 var pname = $(data.responseText).find('td').eq(0).text().trim();

 if (error === "Aucune information trouvée" || pname === "") {
  pdatas.adv_name.push(data.licence+" introuvable");
  pdatas.adv_club.push("?");
  pdatas.adv_cat.push("?");
  pdatas.pts_adv_encours.push(0);
  pdatas.pts_adv_mensuels.push(0);
  pdatas.matchs_rejetes.push(1);
 } else {
  pdatas.adv_name.push(pname.replace(/\'/g,' '));
  pdatas.adv_club.push($(data.responseText).find('td').eq(6).text().trim().replace(/\s+/g," ").replace(/\'/g,' '));
  pdatas.adv_cat.push($(data.responseText).find('td').eq(10).text().trim());
  pdatas.pts_adv_encours.push($(data.responseText).find('td').eq(16).text().trim());
  pdatas.pts_adv_mensuels.push($(data.responseText).find('td').eq(21).text().trim());
  pdatas.matchs_rejetes.push(0);
 }
 checked_matchs++;
 if (checked_matchs == pdatas.matchs_count) {
  $("#loader").hide();
  return calc_points();
 }
}

//calculate results
function calc_points() {
    ptsGagnes = 0;
    ptsPerdus = 0;
    var ecart=0;
    var pts_estimes=$("#pts_actuels").text().trim();
    var newTotPts = parseFloat(pts_estimes);
    var totMatch = pdatas.matchs_count;
    pdatas.pts_gagnes = [];
    pdatas.ecart=[];
    pdatas.match_result=[];
    pdatas.matchs_gagnes=0;
    pdatas.matchs_perdus=0;
    pdatas.rejetes=0;

    var res = 0;
    for (var i = 0; i < totMatch; i++) {
        var licence = pdatas.licence_arr[i];
        // verifie le resultat du match
        if (pdatas.matchs_rejetes[i] == 1) {
            pdatas.ecart.push(0);
            pdatas.match_result.push("R");
            pdatas.pts_gagnes.push(0);
            pdatas.rejetes++;
        } else {
            // calcul ecart de points 
            var ecart = (parseFloat(pdatas.pts_adv_mensuels[i]) - parseFloat(pdatas.pts_mensuels));
            pdatas.ecart.push(ecart);
            var victory = $('input[name="resultat'+i+'"]').attr("checked");     
            if (victory === true) {
                pdatas.matchs_gagnes++;
                pdatas.match_result.push("V");
                res = ajouterVictoire(pdatas.pts_adv_mensuels[i], pdatas.pts_mensuels, pdatas.coef);
                pdatas.pts_gagnes.push(res);
            } else {
                pdatas.matchs_perdus++;
                pdatas.match_result.push("D");
                res = ajouterDefaite(pdatas.pts_adv_mensuels[i], pdatas.pts_mensuels, pdatas.coef);
                if (res > 0) {
                    pdatas.pts_gagnes.push('-'+res);
                } else {
                    pdatas.pts_gagnes.push(res);
                }
            }
        }
    }
    // calcule general de la difference de points
    newTotPts += ptsGagnes - ptsPerdus; // ajoute les points gagnes au total des matchs
    var differencePts = (parseFloat(newTotPts) - parseFloat(pts_estimes));
    pdatas.new_tot_pts = newTotPts;

    $("#compet_title").empty().append('<b>Compétition :</b> ' + pdatas.compet_name);
    $("#compet_coef").empty().append('<b>Coefficient :</b> ' + pdatas.coef);
    $("#calcres_matchs_joues").empty().append(totMatch);
    $("#calcres_matchs_gagnes").empty().append(pdatas.matchs_gagnes);
    $("#calcres_matchs_perdus").empty().append(pdatas.matchs_perdus);
    $("#calcres_matchs_rejetes").empty().append(pdatas.rejetes);
    $("#calcres_pts_gagnes").empty().append(ptsGagnes);
    $("#calcres_pts_perdus").empty().append(ptsPerdus);

    if (differencePts > 0) {
        $("#pts_resultat").empty().append("+" + differencePts);
    } else {
        $("#pts_resultat").empty().append(differencePts);
    }
    $("#new_rank").empty().append(newTotPts + " points");

    //print results
    $("#calculator_results").show();
    $("#loader").hide();
    $('#calcres_matchs_joues').scrollTo(1000);
}

the resulting array of infos in my pdatas object (in the calc_points function) is in the wrong order for exemple, i have the name of my player 2 attached to the licence number of the player 1 in the original pdatas.licence_arr ....

how can i do to keep the order from the original pdatas.licence_arr ?

and maybe show me other errors/improvements :)

thx


If you want to enforce order, use an array. If you want named values in there, use an array os arrays, e.g. [['key1', 'val1'], ['key2', 'val2']]. However, this is kind of messy and you cannot access elements by key without iterating over the array.

So simply change your code that it does not depend on the order of the entries in your object. You cannot ensure AJAX requests called in a certain order get the response in the same order anyway - it's asynchronous. While you could use asynchronos ajax (sjax? :p) requests, you really don't want to do that. They hang some older browsers and if you send multiple right after each other the user will have to wait for all requests to complete before he can do anything.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜