次の例を挙げます。
var animal= null;
$.post("ajax.php",{data: data}, function(output){
animal = output.animal;
},"json");
alert(animal);
原則として、私は変数がajax関数の成功コールバックの外で何かを返すことを望み、それを投稿の外で宣言しました。ただし、それでも「null」が返されます。私は何が間違っているのですか?
$.post()
非同期です。だからあなたはあなたが望むことをすることができません。その代わりに、以下のようなコールバック関数を使用する必要があります。
var animal= null;
$.post("ajax.php",{data: data}, function(data){
// this callback will execute after
// after finish the post with
// and get returned data from server
animal = data.animal;
callFunc(animal);
},"json");
function callFunc(animal) {
alert(animal);
}
問題は、$。postは定義上非同期であるため、success関数の前にalertコマンドが実行されていることです。
必要なことを行うには、次のような同期リクエストを使用する必要があります(リクエストが終了するまでコードは実行されません)。
var animal = null;
$.ajax({
url: 'ajax.php',
async: false, // this is the important line that makes the request sincronous
type: 'post',
dataType: 'json',
success: function(output) {
animal = output.animal;
}
);
alert(animal);
幸運を!