在等待Ajax响应时调用循环的javascript函数

在等待Ajax响应时调用循环的javascript函数

问题描述:

我有两个.asp脚本 - 第一个将sys.tables和sys.views的内容复制到SQL中的另一个表。第二届脚本计算(从newtable的/(COUNT(从SYS.TABLES从sys.views计数())+ COUNT(*)))完成百分比在等待Ajax响应时调用循环的javascript函数

* 100

我有一个功能调用第一个脚本。

function importTablesAndViews() 
{ 
    xmlhttpImportTablesAndViews=GetXmlHttpObject(); 

    if (xmlhttpImportTablesAndViews==null) 
    { 
     alert ("Your browser does not support XMLHTTP!"); 
     return; 
    } 
    url="importtablesandviews.asp"; 
    url=url+"?sid="+Math.random(); 

    xmlhttpImportTablesAndViews.onreadystatechange=function(){if (xmlhttpImportTablesAndViews.readyState==4){ 
     var aspResponse = xmlhttpImportTablesAndViews.responseText; 
    alert(aspResponse); }} 
    xmlhttpImportTablesAndViews.open("GET",url,true); 
    xmlhttpImportTablesAndViews.send(null); 
} 

我有另一个函数来调用进度脚本

function refreshImportProgress() 
{ 
    //alert('Refresh...'); 
    xmlhttpRefreshImportProgress=GetXmlHttpObject(); 

    if (xmlhttpRefreshImportProgress==null) 
    { 
     alert ("Your browser does not support XMLHTTP!"); 
     return; 
    } 
    url="importtablesandviewsprogress.asp"; 
    url=url+"?sid="+Math.random(); 

    xmlhttpRefreshImportProgress.onreadystatechange=function(){if (xmlhttpRefreshImportProgress.readyState==4){ 
     var aspResponse = xmlhttpRefreshImportProgress.responseText; document.getElementById('progressDiv').innerHTML = aspResponse; }} 
    xmlhttpRefreshImportProgress.open("GET",url,true); 
    xmlhttpRefreshImportProgress.send(null); 
} 

我希望能够做的是呼吁3秒的间隔refreshImportProgress()函数从importTablesAndViews内什么()函数。

这可能吗?我曾尝试使用谷歌同步阿贾克斯请求,但迄今没有多少运气。

onreadystatechange处理器的xmlhttpRefreshImportProgressrefreshImportProgress启动一个定时器(setTimeout)(只要进度低于100%):

function refreshImportProgress() { 
    // ... 

    xmlhttpRefreshImportProgress.onreadystatechange = function() { 
     if (xmlhttpRefreshImportProgress.readyState == 4) { 
      document.getElementById('progressDiv').innerHTML = xmlhttpRefreshImportProgress.responseText; 

      var progress = parseInt(xmlhttpRefreshImportProgress.responseText, 10); 
         // ↑ this assumes the value of responseText is a integer only or a integer with a percentage symbol (44%) 

      if (progress < 100) { 
       setTimeout(refreshImportProgress, 3000); 
      } 
     } 
    } 

    // ... 
} 

而且在importTablesAndViews()就叫refreshImportProgress发送请求后:

function importTablesAndViews() { 
    // ... 
    xmlhttpImportTablesAndViews.send(null); 

    refreshImportProgress(); 
} 

道歉,如果我误解了这个问题。 但我不确定在3秒计时器上如何处理Ajax是最好的方法。例如,如果您的浏览器非常慢,则无法保证第一种方法的更改能够及时完成。另外3秒钟等待快速浏览器可能是不必要的。

如果你必须这样做,那么只需要调用的setTimeout() http://www.w3schools.com/jsref/met_win_settimeout.asp

它似乎更容易,你应该实施每当需要时间的问题都解决了被称为承诺。 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise

甚至是一个事件监听器。这里有一份清单。 http://www.w3schools.com/jsref/dom_obj_event.asp

不应该真的需要使用超时,除非你只是想延迟异步的事情,直到下一个滴答声。