AJAX异步设置为false阻止页面,否则无法获取值

时间:2013-09-18 03:29:30

标签: javascript jquery ajax performance asynchronous

我在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异步。

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

由于

1 个答案:

答案 0 :(得分: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