function check_timer(){
//get product ids
var product_ids= document.getElementsByClassName("product_id");
//create for loop
for(var i=0; i<product_ids.length; i++){
var product_id= product_ids[i].innerHTML;
$.ajax({
//send product id to check
url: "check_last_timer.php",
type: "post",
data: {product_id: product_id},
success: function(end_time){
//trying to get product_id here
//$("#timer"+product_id).html(end_time);
}
})
}
}
我正在尝试在成功函数中获取我的产品id。正如你所看到的,我有一个for循环,它在每次运行时向"check_last_timer.php“发送product_id,例如,1,2,3…10。问题是我如何在成功函数中取回1,2,3...10。每次运行for循环时,我都会得到最后一个产品id,即10。
发布于 2012-07-03 20:28:44
您不能从闭包内部使用在闭包外部声明的循环变量。
在使用jQuery时,请使用.each
function check_timer() {
$('.product_id').each(function() {
var product_id = this.innerHTML; // or $(this).html()
$.ajax({
//send product id to check
url: "check_last_timer.php",
type: "post",
data: {product_id: product_id},
success: function(end_time){
$("#timer" + product_id).html(end_time);
}
});
});
}
发布于 2012-07-03 20:26:11
这是因为AJAX调用顾名思义是异步的。for循环继续对ajax调用进行排队,因此您将获得最后一个id为10,因为for循环太快,而ajax调用需要时间才能完成。
你能做的就是发送product_id到request。成功地从服务器获取它,然后进行处理
https://stackoverflow.com/questions/11310705
复制相似问题