0

我有以下语法可以 100% 正确工作并填充相应的复选框:

for (var i = 1; i < 30; i++) {     
$.post('get_sku_prices', {data: $('#product'+i).val()},function(result) {
    $('#price'+i).val(result);
    $('#adjustedprice'+i).val(result);
});
alert(i);
}

如前所述,工作正常。如果我删除警报并且只有

for (var i = 1; i < 30; i++) {   
$.post('get_sku_prices', {data: $('#product'+i).val()},function(result) {
    $('#price'+i).val(result);
    $('#adjustedprice'+i).val(result);
});

}

没有警报就不会填充字段,就像警报强制页面刷新一样。

有任何想法吗?提前致谢...

4

4 回答 4

2

这是因为在第一种情况下alert()是阻塞的,需要关闭循环才能继续。

在第二种情况下(没有警报),ajax 调用会立即执行而不等待响应。即当第一个请求的响应(i=1)到达时,i不一定1

您可以通过使用$.ajax和它的context选项来修复它。

例如:

for (var i = 1; i < 30; i++) {     
    $.ajax({
        type: 'POST',
        url: 'get_sku_prices',
        data: {data: $('#product'+i).val()},
        context: {index: i}, // this value will be available in success as "this"
        success: function(result) {
            $('#price'+this.index).val(result); // use "this.index" here
            $('#adjustedprice'+this.index).val(result);
        }
    });
}
于 2013-04-24T15:21:12.517 回答
1

您可以创建自己的范围函数,如下所示:

for (var i = 1; i < 30; i++) {
    (function (index) {
        $.post('get_sku_prices', {
            data: $('#product' + index).val()
        }, function (result) {
            $('#price' + index).val(result);
            $('#adjustedprice' + index).val(result);
        });
    })(i)
}
于 2013-04-24T15:32:07.137 回答
0

将 Count 发送到服务器并尝试将计数返回到您的结果中,并根据从结果中收到的计数而不是来自 for 循环的计数进行更改。

于 2013-04-24T15:26:57.523 回答
0

尝试在函数执行中添加一些延迟

var i=0;
function postRequest(i){
$.post('get_sku_prices', {data: $('#product'+i).val()},function(result) {
    $('#price'+i).val(result);
    $('#adjustedprice'+i).val(result);
});
setTimeout(function(){
    postRequest(i++);
},1000);
}
于 2013-04-24T15:29:32.923 回答