javascript - 如何访问ajax成功函数中的循环变量?
问题描述
我有一个同时发出 ajax 请求的代码。但是我想在 ajax 请求的成功函数中访问 i(loop variable) 的值。这是我的代码:
arr=['one','two','three']
value="wow"
for(var i = 0;i<arr.length;i++){
$.ajax({
url: '/some_url',
method:'POST',
data:{
'something':arr[i],
'onething':value
},
async: true,
success: function(data) {
if(data.error==true){
//Here, i need the value of i for some reason
}
else{
}
},
error:function(error){
console.log(error);
}
});
}
我在问我这样做是否完全错误。或者有什么办法可以做到这一点?
解决方案
在您的解决方案中,javascript 流不会保留i
. 您需要创建closure
以使 javascript 保留i
. 试试这个,
arr=['one','two','three']
value="wow"
for(var i = 0;i<arr.length;i++){
(function(i){ // self invocation functino
$.ajax({
url: '/some_url',
method:'POST',
data:{
'something':arr[i],
'onething':value
},
async: true,
success: function(data) {
if(data.error==true){
//`i` should correctly here now
}
else{
}
},
error:function(error){
console.log(error);
}
});
})(i); // we are suppling the value of `i` here
}
注意 for 循环的主体。
推荐阅读
- go - 下载依赖项时出错
- html - 覆盖动画的 CSS 类不起作用
- mysql - 关于“UNION ALL”语句的问题,MYSQL
- javascript - 在 JQuery 中添加变换(rotateZ)和左动画
- sql - 视图与索引视图或物化视图之间的区别
- simulation - 如何使用模拟时间来触发模块中的动作?
- java - 如何确定测试是在本地运行还是在远程服务器上运行
- php - 使用 /blogo/testing-view_5.html 清理 url,所有 php 文件都是 .html .htaccess
- c# - 如何在 ASP.NET MVC 存储库模式中使用“Sql in”
- couchbase - Couchbase 创建了巨大的 GSI 索引文件