SetInterval延迟Ajax调用

时间:2013-03-07 08:42:22

标签: jquery setinterval

我有这个ajax呼叫,这是每10秒重复一次的呼叫。这非常有效但是,Visits计数器仅在页面加载后10秒更新。在那之前,它是空的。如果我把它设置为60秒,这是我认为更实际的,那么该区域是空白60秒,然后才会出现数据。

如何修改此值以在页面加载时立即获取Visits的值,然后每10秒连续刷新一次?

<script type="text/javascript">
var Visits = 0; 

$(document).ready(function() {
  $("#counter").flipCounter(); 
  setInterval("ajaxd()",10000);
});

function ajaxd(){   // this function is called only after 10 seconds after page load
  $.ajax({
  type: "POST",
  cache:false,
  url: "getVisits.asp?dx=1,   // returns a number
  dataType: "text",
  data: "",
  success: function(data){
       Visits= parseFloat(data).toFixed(2);
  }
});
/// update value in <div>

$("#counter").flipCounter(
"startAnimation", // scroll counter from the current number to the specified number
{
start_number: 0, // the number we want to scroll from
end_number: Visits, // the number we want the counter to scroll to
numIntegralDigits: Visits.length-3, // number of places left of the decimal point to maintain
numFractionalDigits:2, // number of places right of the decimal point to maintain
easing: jQuery.easing.easeOutCubic, // this easing function to apply to the scroll.
duration: 3000 // number of ms animation should take to complete
});   
}

最后,这个计数器出现的部分是:

<div id="counter" class="bb_box">
<input type="hidden" name="counter-value" value="00.00"/>
</div>

2 个答案:

答案 0 :(得分:0)

变化

$(document).ready(function() {
  $("#counter").flipCounter(); 
  setInterval("ajaxd()",10000);
});

$(document).ready(function() {
  $("#counter").flipCounter(); 
  setInterval(ajaxd,10000);
  ajaxd();  // add this to call ajax once immediately
});

将此代码块移动到脚本块的末尾,以避免调用未定义的函数。

<强>更新 你可以尝试这样:

var Visits = 0; 

function ajaxd(){   
  $.ajax({
  type: "POST",
  cache:false,
  url: "getVisits.asp?dx=1,   // returns a number
  dataType: "text",
  data: "",
  success: function(data){
       Visits= parseFloat(data).toFixed(2);
       $("#counter").flipCounter("setNumber", Visits);
  }
});

$(document).ready(function() {
  $("#counter").flipCounter(); 
  setInterval(ajaxd, 10000);
  ajaxd();
});

答案 1 :(得分:0)

试试这个(参见ajaxd()在函数之后)

setInterval(function() {
ajaxd();

}, 10000);

function ajaxd(){   // this function is called only after 10 seconds after page load
  $.ajax({
  type: "POST",
  cache:false,
  url: "getVisits.asp?dx=1,   // returns a number
  dataType: "text",
  data: "",
  success: function(data){
       Visits= parseFloat(data).toFixed(2);
  }

 ajaxd();