0

次の例を挙げます。

var animal= null;

$.post("ajax.php",{data: data}, function(output){
     animal = output.animal;
},"json");

alert(animal);

原則として、私は変数がajax関数の成功コールバックの外で何かを返すことを望み、それを投稿の外で宣言しました。ただし、それでも「null」が返されます。私は何が間違っているのですか?

4

2 に答える 2

4

$.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);
}
于 2012-08-06T19:22:25.703 に答える
2

問題は、$。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);

幸運を!

于 2012-08-06T19:30:01.093 に答える