我有一个每5秒运行一次的脚本,作为轮询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中的“数据”参数提交增加值吗?
答案 0 :(得分:0)
每次执行调用state.recordId
方法的函数时,都必须确保没有反复设置.ajaxPoll()
。 state = ...
应该在运行.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
答案 1 :(得分:0)
可能在匿名函数内部关闭状态对象的副本,该函数始终以其初始值开始,除非在关闭/创建之前在闭包之外进行更改。要进行验证,只需使用以下
替换该增量行window.recordId = window.recordId + 1 // Making it global variable
您可以在此处找到关于闭包的基本介绍http://msdn.microsoft.com/en-us/magazine/cc163419.aspx
您可以将状态对象作为变量传递给successCondition匿名函数吗?这样你就可以得到实际的副本
答案 2 :(得分: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'));
}
});