0

我在 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异步,它也会阻止整个页面继续。

请帮助:如何更新变量,同时不要阻止页面?

谢谢

4

1 回答 1

0

您仍然可以在异步成功处理程序回调中设置变量,但是任何立即需要该变量值的代码也必须在回调中或从回调中调用。这就是您处理异步响应的方式。

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 yet
于 2013-09-18T03:34:37.190 回答