昨天问了一个关于json的问题
链接:How to return an array from jQuery ajax success function and use it in a loop?
答案之一是这个
setInterval(updateTimestamps,30000);
var ids = new Array();
function updateTimestamps(){
$(".timestamp").each(function(i){
var obj = new Object();
obj.id = $(this).attr("postID");
obj.timestamp = $(this).attr("postdate");
ids.push(obj);
}
$.post("http://site.com/ajax/humanTime.php", {"time": ids}, function(data) {
for (i = 0; i < data.length; i++) {
$("#" + data[i].id).html(data[i].content);
}
}, "json");
}
这个脚本的问题是数据是重复的
第一次执行时是这样的
Array
(
[0] => Array
(
[id] => 26629
[timestamp] => 1332273712
)
[1] => Array
(
[id] => 26628
[timestamp] => 1332243526
)
[2] => Array
(
[id] => 26627
[timestamp] => 1332237777
)
第二次是
Array
(
[0] => Array
(
[id] => 26629
[timestamp] => 1332273712
)
[1] => Array
(
[id] => 26628
[timestamp] => 1332243526
)
[2] => Array
(
[id] => 26627
[timestamp] => 1332237777
)
[3] => Array
(
[id] => 26629
[timestamp] => 1332273712
)
[4] => Array
(
[id] => 26628
[timestamp] => 1332243526
)
[5] => Array
(
[id] => 26627
[timestamp] => 1332237777
)
)
我尝试使用 var ids= Array(); , vas ids = [];但是那个剂量起作用了
最佳答案
重置数组的快捷方式:ids.length = 0;
。所以
function updateTimestamps(){
ids.length = 0;
// [...]
}
关于javascript - 如何清空数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9800104/