在ajax完成之前运行ajax之后的jQuery代码 [英] jQuery code after ajax runs before ajax is completed

查看:121
本文介绍了在ajax完成之前运行ajax之后的jQuery代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$("form#go").submit(function(){
    var $this = $(this);
    var btn = $this.find("button");
    btn.text("Searching").attr('disabled','disabled');
    $.ajax({
        url:
        type:
        data:
        dataType:
                    success:function(result){
             //code....
                    }
    });
    btn.text("Go").removeAttr('disabled');

    return false;
});

这是我的代码结构.问题是btn.text("Go!").removeAttr('disabled');立即运行,尽管ajax部分需要500毫秒才能完成,但我看不到禁用的按钮和按钮文本的更改.

This is my code structure. The problem is btn.text("Go!").removeAttr('disabled'); runs immediately and I can't see the disabled button and the change of button text , although the ajax part takes 500ms to finish.

如果我将最后一部分更改为

If I change the last part to

setTimeout(function () {
     btn.text("Go").removeAttr('disabled');
 }, 1000);

然后我可以看到更改1秒钟,因此我猜我的代码可以正常工作.但是我不知道为什么它要在ajax调用之前运行.

Then I can see the change for 1 second, so I guess my code works. But I have no idea why it runs before the ajax call.

推荐答案

在ajax成功调用中对其进行调用,因为ajax调用是异步的,因此您的代码将在ajax调用完成之前得到执行:

Call it in ajax success call back, as ajax call is async so your code will get executed before ajax call completes:

$.ajax({

............
...........
success: function()
{
setTimeout(function () {
     btn.text("Go").removeAttr('disabled');
 }, 1000);
}

});

这篇关于在ajax完成之前运行ajax之后的jQuery代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆