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

我更喜欢使用回调来完成这项工作,因为它实现了完全相同的结果,而实际上并没有使其同步。我使用成功:回调,然后将回调作为参数传入。

 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 回答