当我执行循环时,AngularJs/Ajax索引正在改变
AngularJs/Ajax index is changing when i do a loop
我有一个从2 ajax请求创建的数组。
var myId = 13;
var array = [];
var checkIFfollowing = function(id, username){
UserService.checkIfFollowing(id, myId)
.success(function (data) {
var post = {
is_following : data, //boolean
username : username
}
array.push(post);
}).
error(function(error) {
//error
});
}
UserService.GetUserById(user_id)
.success(function (data) {
angular.forEach(data, function(post){
checkIfFollowing(post.id, post.username)
})
}).
error(function(error) {
//error
});
数据结构总是这样返回:
[{id:1, username:'ed'},{id:2, username:'joe'},{id:3, username:'bob'}]
但是在循环之后索引改变了,但是很多时候它们都是相同的索引。有没有办法让它始终保持一致
第二个userservice . checkifollowing()异步返回结果,因此填充数组的顺序将发生变化。一种有效的方法是维护一个索引,并在处理完所有项后按索引对数组进行排序。示例代码如下:
var myId = 13;
var array = [];
var dataLength;
var checkIFfollowing = function (index, id, username) {
UserService.checkIfFollowing(id, myId)
.success(function (data) {
var post = {
is_following: data, //boolean
username: username,
index: index
}
array.push(post);
if (dataLength - 1 === index) {
array.sort(function (a, b) { return a.index - b.index })
}
}).error(function (error) {
//error
});
}
UserService.GetUserById(user_id)
.success(function (data) {
dataLength = data.length;
data.forEach(function (post, index) {
checkIfFollowing(index, post.id, post.username)
})
}).error(function (error) {
//error
});
相关文章:
- 使用ajax时,php中未定义的索引
- 当索引页面上的项目单击时发布 ajax
- 尝试使用AJAX将JavaScript变量传递给PHP,但得到'未定义的索引'
- jQuery ajax请求,将索引数组作为关键字字符串
- 通过AJAX访问时,$_POST中出现未定义的索引错误
- Ajax / PHP 注意:未定义的索引:
- 从索引数据库中的 ajax 调用缓存 JSON,检查更改
- 链接到索引并触发特定的 ajax 加载
- 如何修复此未定义的索引错误?Ajax 到 PHP
- 未定义索引:通过AJAX传递的PHP变量
- 想要上传和解析 json 文本,并通过使用 ajax 单击按钮将其加载到我的索引页
- Rails AJAX 销毁 - 重新渲染索引问题
- AJAX 异步返回错误的索引
- 未定义的索引,同时尝试回显变量 $_SESSION,PHP jquery ajax,
- 通过 ajax 发送带有字母数字索引名称的数组
- AJAX调用中缺少POST参数会导致PHP脚本中出现未定义的索引警告
- 如何在ExtJs 5.0中通过ajax调用在更新选项卡后强制重新索引
- jquery ajax请求中出现未定义索引错误
- 未定义的索引:处理此 AJAX 代码时的名称
- 如何防止搜索引擎索引ajax生成的内容