javascript - ajax jquery同步回调成功

标签 javascript jquery ajax 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;
    }

根据代码注释中描述的问题,对于这种情况最好进行哪些更改?

最佳答案

您需要为这样的同步请求设置 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;
}

参见 here详情

关于javascript - ajax jquery同步回调成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1572610/

相关文章:

javascript - AngularJS 获取外部 JSON 的问题

javascript - 过滤列表而不是 D3 中的选择下拉列表

javascript - Twitter API 调用仅使用 javascript 获取 OAuth 的 access_token

javascript - 谷歌翻译API使用js翻译页面

html - 在ajax中用jquery更新css?

javascript - Symfony2 和 jquery ajax

javascript - ExtJS Ajax 请求超时对 Internet Explorer 没有影响

javascript - 如何在 python 中访问 html 表单值 - web2py

javascript - Javascript执行上下文总是有两个阶段(创建和执行)吗?

javascript - document.hasOwnProperty ("hidden") 返回 false 但文档隐藏了该属性