jQuery 异步加载问题

peakcary 2011-08-31 11:46:01
$(document).ready(function() {
userList();
alert(hashUser.size());
});

function userList() {
$.ajax({
type : "POST",
dataType : "json",
url : "ScoreJson/listClassmates.action",
success : function(data) {
$.each(data.userList, function(i, item) {
hashUser.add(item.userId, item.realName);
});

},
error : function() {
alert("action_error");
}
});
}

请教童鞋们 hashUser.size() 怎么总是为0呢 明明是有数据的 是不是异步加载的数据在$(document).ready不能立即获得到,有没有什么解决方案呢
...全文
108 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
燥动的心 2011-08-31
  • 打赏
  • 举报
回复
是的,不然就不是异步了,有需求的情况下可以改成同步
我是来接分的 2011-08-31
  • 打赏
  • 举报
回复
怎么可能立即获得
我是来接分的 2011-08-31
  • 打赏
  • 举报
回复
function userList() {
$.ajax({
type : "POST",
dataType : "json",
url : "ScoreJson/listClassmates.action",
success : function(data) {
$.each(data.userList, function(i, item) {
hashUser.add(item.userId, item.realName);
});
alert(hashUser.size());
},
error : function() {
alert("action_error");
}
});
}

你都说是异步的了
我是来接分的 2011-08-31
  • 打赏
  • 举报
回复
async(默认: true) 默认设置下,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为 false。注意,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。
function userList() {
$.ajax({
type : "POST",
dataType : "json",
async:false,
url : "ScoreJson/listClassmates.action",
success : function(data) {
$.each(data.userList, function(i, item) {
hashUser.add(item.userId, item.realName);
});

},
error : function() {
alert("action_error");
}
});
}
yibiaott 2011-08-31
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 peakcary 的回复:]

引用 3 楼 pj100 的回复:

是的,不然就不是异步了,有需求的情况下可以改成同步


同步怎么处理呢
[/Quote]
同步,还要AJAX干什么。
peakcary 2011-08-31
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 pj100 的回复:]

是的,不然就不是异步了,有需求的情况下可以改成同步
[/Quote]

同步怎么处理呢
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 ly89924 的回复:]

function userList() {
$.ajax({
type : "POST",
dataType : "json",
url : "ScoreJson/listClassmates.action",
success : function(data) {
$.each(data.userList, function(i, item) {
hashUser.add(item……
[/Quote]

+++

ajax是异步请求的,userList()函数执行到send()的时候,代码不会等待你的ajax的返回结果就立即返回了,接着往下运行下一句了。

如果你的ScoreJson/listClassmates.action执行速度非常快,而且是在本地测试的情况,有可能会看到hashUser.size()的结果不是0

87,907

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧