4

私はajax呼び出しを行うこの関数を持っています。コードコメントの最後のチャンクで問題を説明しています。

    function doop(){
            var that = this;
            var theold = "theold";
            var thenew = "thenew";

            $.ajax({
                    url: 'doop.php',
                    type: 'POST',
                    data: 'before=' + theold + '&after=' + thenew,
                    success: function(resp) {
                            if(resp == 1) {
                                    $(that).siblings('.theold').html(thenew);
                            }
                    }
            });

            // I have some code here (out of the ajax) that **further** changes 
            // the .theold's html beyond what it was changed inside ajax success
            // but the change depends on whether the resp (inside the success 
            // function) returned 1 or not, so this code out here depends on the ajax
            // so it looks like I have to turn this ajax call into a sync ajax

            return false;
    }

コードコメントに記載されている問題に基づいて、この状況に最適な変更は何ですか?

4

3 に答える 3

15

次のような同期リクエストには async: false を設定する必要があります。

function doop(){
        var that = this;
        var theold = $(this).siblings('.theold').html();
        var thenew = $(this).siblings('.thenew').val();

        $.ajax({
                async: false,
                url: 'doop.php',
                type: 'POST',
                data: 'before=' + theold + '&after=' + thenew,
                success: function(resp) {
                        if(resp == 1) {
                                $(that).siblings('.theold').html(thenew);
                        }
                }
        });

        // some other code

        return false;
}

詳細はこちら

于 2009-10-15T14:14:09.007 に答える
1

stefita が指摘したように Ajax 呼び出しを同期に設定するか、コードを成功コールバックに移動します。なんでできないの?それが別の Ajax 呼び出しであっても、実行できます。それらをネストすることができます。これまでに提供された情報では (問題のあるコードが表示されず、プロジェクトに関する十分なドメイン知識もありません)、実際には問題はありません。

于 2009-10-15T14:17:28.937 に答える
0

実際に同期させなくてもまったく同じ結果が得られるため、コールバックを使用してジョブを実行することを好みます。私は success:callback を使用し、コールバックをパラメーターとして渡します。

 function getData(callback) {
      $.ajax({
          url: 'register/getData',
          data: "",
          dataType: 'json',
          success: callback
      });
  }

次に、この関数を次のように呼び出します。

  getData(function(data){
    console.log(data); //do something 
  });
于 2013-04-18T02:55:37.117 に答える