javascript - JQuery:为什么ajax请求在beforeSend中的代码执行完成之前执行?

标签 javascript jquery html ajax

这是我的代码。基本上我有一个 Reload.gif,我想在发送 ajax 请求来重新加载数据之前开始在我的页面上播放它。然而最终发生的事情是它只会在调用我的成功函数后才开始播放。时间线是这样的:

0:00 秒:1 已记录到控制台

0:00 秒:2 已记录到控制台

0:10 秒:3 已记录到控制台

0:10 秒:GIF 开始播放。

这没有意义,是设置 img 的 src 异步还是其他什么? 图片代码:

<img id="reloadIcon" src="/img/Reload.png" style="width: 25px; height: 25px"/>

jQuery.ajax({
    url: url,
    type: 'GET',
    timeout: 20000,
    beforeSend: function() {
        console.log(1);
        document.getElementById('reloadIcon').src = "/img/Reload.gif";
        console.log(2);
    },
    success: function (result) {
        console.log(3);
    }
});

最佳答案

加载$.ajax()之前的图像称呼。切换 CSS display <img>的属性(property)元素位于 beforeSend函数,而不是更改 .src <img>的元素。

jQuery.ajax({
    url: url,
    type: 'GET',
    timeout: 20000,
    beforeSend: function() {
        console.log(1);
        document.getElementById('reloadIcon').style.display = "block";
        console.log(2);
    },
    success: function (result) {
        document.getElementById('reloadIcon').style.display = "none";
        console.log(3);
    }
    , error: function() {
        document.getElementById('reloadIcon').style.display = "none";
    }
});

关于javascript - JQuery:为什么ajax请求在beforeSend中的代码执行完成之前执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45579148/

相关文章:

基于div内容的jQuery克隆

javascript - 两个导航都出来了,如何在点击第一个导航时隐藏第二个导航?

javascript - JQuery 插件优化

jquery - 修复了在 Chrome 或 MS Edge 中不显示的图像

javascript - 当字符串包含 src =""或 id =""属性时,不能 $.parseJSON()

javascript - 如何获取图像的clientHeight?

jquery - select2 依赖下拉菜单超出最大调用堆栈

javascript - Node JS - 在 Jade 中扩展布局时出错

javascript 数组 - 用单引号分隔值和值的值

php - 如何在 jQuery 中将多个类应用于多个 Div