如何在JQuery中伪造AJAX开始/结束事件? [英] How do I fake AJAX start / end events in JQuery?

查看:102
本文介绍了如何在JQuery中伪造AJAX开始/结束事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在听ajaxStart()和ajaxStop()来显示/隐藏微调框,并且在编写服务器时正在JS中进行一些模拟AJAX的工作.它只是调用一个函数来使用setTimeout()生成模拟数据.现在,我只是在微调器上手动调用hide()和show(),但是我真的很想告诉JQuery我何时开始和停止请求",并让事件通过这种方式进行,因此当 real ajax请求仍在后台运行时,我不会意外地隐藏()微调框.

I'm listening to ajaxStart() and ajaxStop() to show/hide a spinner, and I'm doing some mock AJAX stuff in JS while servers are being written. It just calls a function to generate mock data with a setTimeout(). For now I'm just manually calling hide() and show() on the spinner, but I'd really like to just tell JQuery when I'm starting and stopping my "request", and have the events go through that way, so I don't accidentally hide() the spinner while a real ajax request is still going in the background.

这可以轻松完成吗?

这是我确定的代码,技巧是保持JQuery.active计数:

This is the code I settled on, the trick is maintaining the JQuery.active count:

function fakeAJAX(f) {
    if(jQuery.active++ === 0 ) {
        jQuery.event.trigger("ajaxStart");
    }
    setTimeout(function () {
        f();
        if(!(--jQuery.active)) {
            jQuery.event.trigger("ajaxStop");
        }
    }, Math.round(Math.random() * 3000 + 250));
}

推荐答案

根据来源,您只需调用以下内容即可:

According to the sources you just need to invoke:

jQuery.event.trigger( "ajaxStart" );

jQuery.event.trigger( "ajaxStop" );

相应地.

http://jsfiddle.net/zerkms/7RVbz/

这篇关于如何在JQuery中伪造AJAX开始/结束事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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