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は非同期であるため、変数pictureは更新されません。このように無効にすると、im.js async全体をロードしても、ページ全体がブロックされます。

助けてください: どうすれば変数を更新できますか? それまでの間、ページをブロックしないでください。

ありがとう

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 に答える