2016-05-13 8 views
0

次のスクリプトは、ajaxリクエストを毎秒2回(setIntervalと500msのタイムアウトを使用して)作成してプログレスバーを更新します。既存のリクエストがまだレスポンスを受信して​​いない場合、ajaxリクエストを作成しないようにisBusyフラグを追加しました。しかし、それは動作しません。もちろん、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' });