我在im.js中使用了一个ajax请求,因此它将从js调用我的PHP服务器并获得反馈。但是,我需要根据.ajax函数的回调更新一个变量,如下所示:
var picture = "<img src='https://www.123.com/pictures/unknown.jpg' width='30' />";
$.ajax({'type':'GET', 'async':false,'url':'https://www.123.com/site/getpic?username=' + username,
'success':function(callback){
picture = "<img src='" + callback + "' width='30' />";
} //ajax success
}); //ajax注意,如果我删除" async : false",变量图片将不会更新,因为ajax是异步的,如果我像这样禁用它,即使我加载整个im.js异步,它也会阻止整个页面继续运行。
请帮助:如何在更新变量的同时,不阻塞页面?
谢谢
发布于 2013-09-18 11:34:37
您仍然可以从异步成功处理程序回调中设置变量,但任何需要该变量的值的代码也必须在回调中或从回调中调用。这就是处理异步响应的方式。
var picture = "<img src='https://www.123.com/pictures/unknown.jpg' width='30' />";
$.ajax({type:'GET',
async:true,
url:'https://www.123.com/site/getpic?username=' + username,
success:function(response){
picture = "<img src='" + response + "' width='30' />";
// code that uses this picture value immediately must be located here
// or called from here
}
});
// code that uses the new value of the picture variable cannot be here
// because the variable's new value is not set yet
// because the ajax call has not yet completed and thus has not called its
// success handler yethttps://stackoverflow.com/questions/18863368
复制相似问题