2010-10-20 42 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')); 
    } 
});