好的,这是你的代码:http: //jsfiddle.net/848AE/1/
查看控制台(我将成功事件更改为失败,但这没关系)。
function test(param) {
console.log('------------------------------');
console.log('param = ' + param);
var tt = [ "a", "b", "c" ];
for ( var i = 0; i < param; i++) {
console.log('Before if-check, i = ' + i);
if (tt[i] == "b") {
console.log('Request start, after if-check i = ' + i);
Ext.Ajax.request( {
url : 'test.do',
method : 'POST',
failure: function(response) {
console.log('Failure start, i = ' + i);
test(1);
console.log('Alert(i) = ' + i);
}
});
// break;
}
}
}
test(3);
从第一个代码记录(循环中没有断字):
------------------------------
param = 3
Before if-check, i = 0
Before if-check, i = 1
Request start, after if-check i = 1
Before if-check, i = 2
POST http://fiddle.jshell.net/_display/test.do 404 (NOT FOUND) ext-all.js:21
Failure start, i = 3
------------------------------
param = 1
Before if-check, i = 0
Alert(i) = 3
如您所见,当您启动请求时,函数并没有停止执行并继续循环工作(i = 2, 3)。因此,当您从服务器获得响应时,变量 i 的值为 3。
然后,您使用参数 1 调用函数,它完成并返回失败函数,但在失败函数范围内,变量 i 的值仍然为 3。
所以,如果我理解正确,你必须在循环中添加中断词,就像在代码注释中一样。
编辑:
如果您想循环执行请求并暂停直到回调执行,则没有记录的属性:
var response = Ext.Ajax.request({
...
async: false,
...
})
结果 async:false :
param = 3
Before if-check, i = 0
Before if-check, i = 1
Request start, after if-check i = 1
POST http://fiddle.jshell.net/_display/test.do 404 (NOT FOUND) ext-all.js:21
Failure start, i = 1
------------------------------
param = 1
Before if-check, i = 0
Alert(i) = 1
Before if-check, i = 2