Javascript函数在IE中工作正常但在chrome和Firefox中没有,除非$(document).ready()启动

时间:2014-03-13 08:36:14

标签: javascript jquery ajax internet-explorer google-chrome

对于我的项目,我需要从远程服务器获取一些数据,以便在表中显示,并使用AJAX每隔X次刷新一次。

实际上它在IE上工作正常,但是当我尝试使用Chrome和Firefox时,AJAX函数无法在$(document).ready()事件中运行...

$(document).ready(function () {
  doLaunch(); // This works
});

setInterval(function () {
  if ($_dragStart == null) {
    doClear(); // working but no AJAX in there

    doRecup(); // not working
   }
}, 10000);


function doLaunch() {
  $.ajax({
    type: 'POST',
    url: 'journalier.aspx/copyDataYesterday',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    complete : function () {
      doRecup(); // working in there
    },
    error: function (xhr, status, error) {
      var err = eval("(" + status + ")");
      alert(err); 
    }
  });
};

function doRecup() {
  $.ajax({
    type: 'POST',
    url: 'journalier.aspx/getDataNav',
    contentType: 'application/json; charset=utf-8',
    data: '{datePlanning:"' + '<%= Session["Planning_Date"].ToString() %>' + '"}',
    dataType: 'json',
    success: function (data) {
       var dateMaj = document.getElementById("MainContent_dateTimePlanning").value; 

       for (i = 0; i < 1000 ; i++) { 
         if (data.d[(i * 5) + 3] == dateMaj) { 
           var objet = document.getElementById(data.d[(i * 5) + 2]); 

           var row = document.getElementById("MainContent_" + data.d[i * 5]); 

           if (row != null) {

             if (data.d[(i * 5) + 1] == "Ressource")
                $(objet).appendTo(row.cells[12].childNodes[0]);
             else if (data.d[(i * 5) + 1] == "Conducteur")
                $(objet).appendTo(row.cells[4].childNodes[0]);
             else if (data.d[(i * 5) + 1] == "Chauffeur")
                $(objet).appendTo(row.cells[6].childNodes[0]);
             else if (data.d[(i * 5) + 1] == "Engin")
                $(objet).appendTo(row.cells[5].childNodes[0]);
             else if (data.d[(i * 5) + 1] == "Chef")
                $(objet).appendTo(row.cells[11].childNodes[0]);
             else if (data.d[(i * 5) + 1] == "Consigne" && data.d[(i * 5) + 4] != null) {
                row.cells[9].childNodes[0].innerText = data.d[(i * 5) + 4];
                row.cells[9].childNodes[1].value = data.d[(i * 5) + 4];
             }
             else if (data.d[(i * 5) + 1] == "Carburant" && data.d[(i * 5) + 4] != null) {
                row.cells[3].childNodes[0].innerText = data.d[(i * 5) + 4];
                row.cells[3].childNodes[1].value = data.d[(i * 5) + 4];
             }

          } 

        }

      } 

      var currDate = new Date();

      var HH = currDate.getHours();
      var MM = currDate.getMinutes();

      var Time = HH + ":" + MM ;

      document.getElementById("MainContent_lblDateLastMaj").innerText = "Dernière Mise à Jour : " + Time;

    },
    error: function (xhr, status, error) {
      var err = eval("(" + status + ")");
      alert(err); 
    },
    complete: function () {
      alert("Complete!");
    }
  });
};

function doClear() {
  for (k = 0; k < document.getElementById("MainContent_divTabProjet").childNodes.length / 2; k++) { 
   for (i = 0; i < document.getElementById("MainContent_tabProjetJourAgence" + k).rows.length; i++) {

     document.getElementById("MainContent_lblCarbu" + i).innerText = ""; 
     document.getElementById("MainContent_lblCarbu" + i).value = "";

   for (j = 0; j < document.getElementById("MainContent_tabProjetJourAgence" + k).rows[i].cells[4].childNodes[0].childNodes.length ; j++) { 

      $(document.getElementById("MainContent_tabProjetJourAgence" + k).rows[i].cells[4].childNodes[0].childNodes[j]).appendTo($("#MainContent_divTabRessources"));

   }

   for (j = 0; j < document.getElementById("MainContent_tabProjetJourAgence" + k).rows[i].cells[5].childNodes[0].childNodes.length ; j++) {

      $(document.getElementById("MainContent_tabProjetJourAgence" + k).rows[i].cells[5].childNodes[0].childNodes[j]).appendTo($("#MainContent_divTabEngins"));

   }

   for (j = 0; j < document.getElementById("MainContent_tabProjetJourAgence" + k).rows[i].cells[6].childNodes[0].childNodes.length ; j++) { 

      $(document.getElementById("MainContent_tabProjetJourAgence" + k).rows[i].cells[6].childNodes[0].childNodes[j]).appendTo($("#MainContent_divTabRessources"));

   }

   document.getElementById("MainContent_lblConsigne" + i).innerText = ""; 
   document.getElementById("MainContent_lblConsigne" + i).value = "";

   for (j = 0; j < document.getElementById("MainContent_tabProjetJourAgence" + k).rows[i].cells[11].childNodes[0].childNodes.length ; j++) {

      $(document.getElementById("MainContent_tabProjetJourAgence" + k).rows[i].cells[11].childNodes[0].childNodes[j]).appendTo($("#MainContent_divTabRessources"));

   }

   for (j = 0; j < document.getElementById("MainContent_tabProjetJourAgence" + k).rows[i].cells[12].childNodes[0].childNodes.length ; j++) { 

       $(document.getElementById("MainContent_tabProjetJourAgence" + k).rows[i].cells[12].childNodes[0].childNodes[j]).appendTo($("#MainContent_divTabRessources"));

   }
  } 
 } 
};

更新:当我在控制台中手动启动该功能时,它可以正常工作。所以问题是该函数不是在间隔中启动,而是doClear函数每10秒启动一次......如果我将doClear函数放在评论中,则doRecup函数每10秒触发一次。

更新2 :如果我这样做,则可行

setInterval(function () {
 if ($_dragStart == null) {
   doClear(); 
 }
}, 10000);
setInterval(function () {
 if ($_dragStart == null) {
   doRecup();
 }
}, 10000);

更新3:现在我这样做:

setInterval(function () {
  setTimeout(function () {
    doClear();
  }, 1);
  setTimeout(function () {
    doRecup();
  }, 1);
}, 10000);

嗯,它远非完美,它当然不推荐,但实际上它的工作原理......

2 个答案:

答案 0 :(得分:0)

我建议您根据ajax请求是否完整来调用该函数。通过在setInterval中调用函数,无论请求是否完成,都将每隔x秒调用一次ajax调用,这在我看来不是一个好习惯。我会做这样的事情:

function doRecup() {
.......
.......
.......
.......
complete: function () {
  setTimeout(function(){
    doRecup();
    doClear();
  }, 10000)
}
.......
.......
.......
}

评论/删除该功能:

setInterval(function () {
  if ($_dragStart == null) {
    //doClear(); // working but no AJAX in there

    //doRecup(); // not working

   }
}, 10000);

答案 1 :(得分:0)

你在任何地方设置var $_dragStart = null ..?因为,对我来说,你的代码正在运作。

无论如何,您可以使用custom ajax error method来了解那里发生的事情......因为您的代码'var err = eval("(" + status + ")");'无法正常工作及其给出错误。

我正在与你分享我的功能

<强> Custom Ajax Error Handling Code:

/**
 * Custom Ajax Error Method
 * 
 * @param jqXHR
 * @param exception
 * @returns {string}
 */
function ajaxError(jqXHR, exception) {
    if (jqXHR.status === 0) {
        alert('Not connected.\nPlease verify your network connection.');
    } else if (jqXHR.status === 404) {
        alert('The requested page not found. [404]');
    } else if (jqXHR.status === 500) {
        alert('Internal Server Error [500].');
    } else if (exception === 'parsererror') {
        alert('Requested JSON parse failed.');
    } else if (exception === 'timeout') {
        alert('Time out error.');
    } else if (exception === 'abort') {
        alert('Ajax request aborted.');
    } else {
        alert('Uncaught Error.\n' + jqXHR.responseText);
    }
}

你可以像这样使用:

<强> Example Code:

function doLaunch() {
    // ajax call
    $.ajax({
        type : 'POST',
        url : 'ajaxCall.php',
        contentType : 'application/json; charset=utf-8',
        dataType : 'json',
        complete : function () {
            console.log('Calling: Ajax Complete doLaunch()');
            doRecup(); // working in there
        },
        error : ajaxError
    });
    // end ajax call
};

你的代码在小提琴中工作。检查它..

小提琴DEMO