栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

jQuery ajax页面重新加载

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

jQuery ajax页面重新加载

来到这里寻求类似的问题,并决定回答,即使对于其他最终可能遇到相同问题的人来说已经很晚了。

我相信您需要的是Ajax全球活动。 请参阅API文档

特别是在这里

全球活动

这些事件在文档上触发,调用可能正在侦听的所有处理程序。您可以像这样监听这些事件:

$(document).bind("ajaxSend", function(){     // You should use "**ajaxStop**" instead of "ajaxComplete" if there are more     // ongoing requests which are not completed yet     }).bind("ajaxStop", function(){     // call your reload function here     });

现在就您的情况而言,如果您使用“ ajaxStop”,则无需绑定“ ajaxComplete”事件,当所有正在处理的Ajax请求完成时将触发此事件。

我在小提琴上复制粘贴了您的原始代码,并在一些日志中添加了我刚推荐的部分。jsfiddle.net/Tt3jk/7/为了测试目的,我

SendData2()
从第一个函数的成功事件中调用了一个类似的函数,以模拟难看的异步请求场景。如果您在实际环境中测试此代码(或将SendData2和您的url一起使用,以响应您的数据类型为“文本”的数据类型,那么您将在控制台上看到的是此输出。(1-是console.log来自
SendData()
,2-来自
SendData2()
):

1-sending...waiting for all requests to complete...1-success:!2-sending...waiting for all requests to complete...1-done:2-success:!2-done:completed now!

实际上,甚至在调用重载函数时,即使在小提琴上(请求有错误),您也可以看到它。如果您使用“
ajaxComplete”,则jQuery内部的重载函数.click()函数将在很早之前被调用。但是,如果使用“ ajaxStop”并在触发“
ajaxStop”事件时调用重载函数,则在所有请求完成后将调用重载函数。

我不知道小提琴是否会在一段时间后消失,所以我也会在没有控制台日志的情况下发布在这里所做的更改:

$(".submit_button").click(function () { popupMessage(); sendData(); //the ajax calls are all in here // consider reloading somewhere else});$(document).bind("ajaxSend", function () { console.log("waiting for all requests to complete..."); // ajaxStop (Global Event) // This global event is triggered if there are no more Ajax requests being processed.}).bind("ajaxStop", function () { // maybe reload here? location.reload();});function popupMessage() { alert("Pop!");}function sendData() {        //a bunch of these:        $.ajax({ "dataType": "text",     "type": "POST",     "data": "temp",     "url": "your url here!",     "beforeSend": function (msg) {         console.log("1-sending...");     },     "success": function (msg) {     console.log("1-success!");     sendData2(); // again },     "error": function (msg) {     console.log("1-error!"); }        }).done(function (msg) { console.log("1-done!");        });}function sendData2() {        //a bunch of these:        $.ajax({ "dataType": "text",     "type": "POST",     "data": "temp",     "url": "your url here!",     "beforeSend": function (msg) {         console.log("2-sending...");     },     "success": function (msg) {     console.log("2-success!"); },     "error": function (msg) {     console.log("2-error!"); }        }).done(function (msg) { console.log("2-done!");        });}

PS。不知道这是一个好习惯,还是不从一个请求中提出另一个请求,可能不是。但是我将其放在此处以显示“
ajaxStop”事件如何延迟触发,直到所有正在进行的请求完成(或至少完成并发生错误)为止…



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/413493.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号