Ajax jquery同步回调成功

Chr*_*ris 4 javascript ajax jquery synchronous

我有这个函数进行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;
    }
Run Code Online (Sandbox Code Playgroud)

根据代码注释中描述的问题,哪种更改最适合这种情况?

ste*_*ita 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;
}
Run Code Online (Sandbox Code Playgroud)

看到这里了解详细信息

  • 嗯,实际上你为success属性声明的函数是回调函数.顺便说一句,我刚刚看到你将结果与一个整数进行比较,但我很确定你默认得到文本,所以它应该是`resp =="1"`. (3认同)
  • 顺便说一句.你可以在ajax请求之外的某个地方定义你的回调函数.可能是你所看到的正是那个 - 一个叫做回调的函数. (2认同)