2010-10-20 44 views
2

我有一个脚本,每5秒运行一次,作为一个轮询AJAX HTTP请求。试图增加一个JavaScript计数器,当使用轮询AJAX http请求

我想通过它来发送一个递增量,对每个请求(1,2,3,4,5,6等)

我有这到目前为止,但代码只需发送“ 1“。

// set the value to 1 
    var state = { 
    recordId: 1 
    }; 

    $.ajaxPoll({ 
     url: "map-service.cfc?method=getpoints", 
     type: "POST", 
      data: state, 
     dataType: "json", 
     successCondition: function(location) { 
     // return result != null; // custom condition goes here. 

    // increment it by 1 
    state.recordId = state.recordId +1 
    alert(state.recordId) 

} 

有谁知道如何通过POST中的'data'参数提交递增值吗?

回答

0

每次执行调用.ajaxPoll()方法的函数时,都必须确保一次又一次不设置state.recordIdstate = ...应该在运行.ajaxPoll()也许像这样的功能的父范围:

(function() {  // <== Our scope 

    // set the value to 1 only once! 
    var state = { 
     recordId: 1 
    }; 

    // The function that runs the poll. Do not set recordId to 1 inside here! 
    var callPoll = function() { 

     $.ajaxPoll({ 
      url: "map-service.cfc?method=getpoints", 
      type: "POST", 
       data: state,    // state.recordId will be 1, 2, 3, ... 
      dataType: "json", 
      successCondition: function(location) { 
       // return result != null;   // custom condition goes here. 

       // increment it by 1 
       state.recordId = state.recordId +1 
       alert(state.recordId) 
      } 
     }); 

    }; 

    $(function() { // <== on doc ready 

     // Your functionality etc...... for example: 
     setInterval(callPoll, 1000); 

    });  
}());    // <== Execute the anonymous function we're using as our scope 
0

可能状态对象的副本匿名函数内关闭,这将始终启动与它的,除非在做出修改初始值在关闭/创建之前关闭之外。为了验证刚刚替换下

window.recordId = window.recordId + 1 // Making it global variable 

,渐进式线你可以找到一个很基本的介绍到这里http://msdn.microsoft.com/en-us/magazine/cc163419.aspx

你可以通过状态对象作为一个变量来successCondition匿名函数闭包?这样你总能得到实际的副本

0

你也可以设置一个数据变量到文档或主体并增加它。

$('body').data('recordId', 1); 

$.ajaxPoll({ 
    url: "map-service.cfc?method=getpoints", 
    type: "POST", 
    data: {recordId: $('body').data('recordId')}, 
    dataType: "json", 
    successCondition: function(location) { 
    // return result != null; // custom condition goes here. 
    // increment it by 1 
    newRecord = $('body').data('recordId'); 
    $('body').data('recordId', newRecord+1); 
     alert($('body').data('recordId')); 
    } 
});