2016-05-13 61 views
0

以下脚本通过每秒发出两次ajax请求(使用setInterval和500 ms超时)来更新进度栏。我添加了isBusy标志,以便在预先存在的请求尚未收到响应时不发出ajax请求。但它不起作用。当然,当我注释掉第19行,这是我设置标志以忙于等待响应的地方,所有工作都可以。我究竟做错了什么?我如何做到这一点,一次只有1个Ajax请求是“活着的”,并等待响应?限制Ajax进度条

01 var exportHandler = { 
02 
03  handlerUrl: '', 
04  intervalId: 0, 
05  isBusy: 0, 
06 
07  start: function() {   
08 
09   // do some set up work 
10 
11   exportHandler.isBusy = 0; // init flag to not busy, not waiting on resp 
12 
13   exportHandler.intervalId = setInterval(function() { 
14 
15    if (exportHandler.isBusy == 1) { 
16     return; // response to previous request not yet rcvd 
17    } 
18 
19    exportHandler.isBusy = 1; // set flag to busy waiting on response 
20 
21    exportHandler.getProgress(); 
22   }, 500); 
23  }, 
24 
25  cancel: function() { 
26   exportHandler.isBusy = 1; // not sure if I need this here??? 
27 
28   if (exportHandler.intervalId != 0) { 
29    clearInterval(exportHandler.intervalId); 
30   } 
31 
32   exportHandler.intervalId = 0; 
33   event.preventDefault(); 
34   return false; 
35  }, 
36 
37  getProgress: function() { 
38 
39   $.ajax({ 
40    url: exportHandler.handlerUrl, 
41    dataType: 'json', 
42    async: true, 
43    data: ..., 
44 
45    error: function (o, st, err) { 
46     exportHandler.isBusy = 0; // err occured so reset flag to not busy waiting on response 
47     
48     // handle error 
49    }, 
50 
51    success: function (job) { 
52     exportHandler.isBusy = 0; // response rcvd so reset flag to not busy waiting on response 
53 
54     showProgress(job, exportHandler); 
55 
56     if (job.JobComplete) { 
57      jobsDone(exportHandler.intervalId, 'export'); 
58     } 
59    } 
60   }); 
61  } 
62 
63 } 

回答

0

在一个区间内执行ajax调用通常是不好的做法。你可以试试这个:

var ajaxCall = function(ajaxData) { 
    // Start loader 
    setLoader('start'); 
    $.ajax({ 
    url: '..', 
    data: ajaxData, 
    success: function(data) { 
     // Stop loader 
     setLoader('stop'); 
     // Do some actions ... 
     // Call this function after 500ms as soon as the function returns it's data 
     setInterval(function() { 

     ajaxCall(data); 
     }, 500); 
    } 
    }); 
} 

// Create a function that handles loader state 
var setLoader = function(mode) { 
    if (mode && mode.length > 0) { 
    switch (mode) { 
     case 'start': 
     // Start loader 
     break; 
     case 'stop': 
     // Stop loader 
     break; 
    } 
    } 
} 

// Call ajaxCall function for the first time 
ajaxCall({ some: 'data' });