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

AJAX async set to false block the page, otherwise can not get the value

本文关键字:获取 设置 异步 false AJAX      更新时间:2023-09-26

我在im中使用ajax请求.js所以它会从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 async,它也会阻止整个页面继续。

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

谢谢

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

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