jQuery ajax 页面重新加载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14632753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:48:18  来源:igfitidea点击:

jQuery ajax Page Reload

jqueryajaxasynchronousreloadsynchronous

提问by btginz

We are making multiple ajax requests to "save" data in a web app, then reload the page. We have run into a situation where (since requests are made asynchronously) the page is reloaded while or before the ajax calls are completed. The simple solution to this was to make the ajax calls with the "async": false option on, forcing synchronous calls. This seems to work, however dialog box code that runs BEFORE any calls are executed delay in running.

我们发出多个 ajax 请求以在 Web 应用程序中“保存”数据,然后重新加载页面。我们遇到过这样的情况(因为请求是异步发出的)在 ajax 调用完成时或之前重新加载页面。对此的简单解决方案是使用 "async": false 选项进行 ajax 调用,强制同步调用。这似乎有效,但是在执行任何调用之前运行的对话框代码会延迟运行。

Any advice is greatly appreciated!

任何意见是极大的赞赏!

Also it should be noted that putting an alert() before the reload ALLOWS the ajax requests to be made. (The alert is obviously delaying the reload long enough for the requests to successfully go through)

还应该注意的是,在重新加载之前放置一个 alert() 允许发出 ajax 请求。(警报显然延迟了重新加载足够长的时间,以便请求成功通过)

UPDATED with code samples:

更新了代码示例:

$(".submit_button").click(function(){ 
    popupMessage();
    sendData(); //the ajax calls are all in here
    location.reload();
});


function sendData() {
    //a bunch of these:
    $.ajax({
    "dataType": "text",
    "type": "POST",
    "data": data,
    "url": url,
    "success": function (msg) {}
    }).done(function( msg ) {

    }); 
}

回答by Kerem

Came across here pursuing a similar problem and decided to answer even though it's quite late for other people who might end up here with same problem.

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

I believe what you need is Ajax global events. See API Documentation

我相信您需要的是 Ajax 全局事件。 请参阅 API 文档

Especially here;

尤其是这里;

Global Events

These events are triggered on the document, calling any handlers which may be listening. You can listen for these events like so:

全球活动

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

$(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

     });

Now for your case, instead of binding "ajaxComplete" event if you use "ajaxStop" this will be triggered when all Ajax requests being processed are finished.

现在对于您的情况,如果您使用“ajaxStop”,则不会绑定“ajaxComplete”事件,这将在处理完所有 Ajax 请求时触发。

I copy-pasted your original code on fiddle and added the part I just recommended with some logs. jsfiddle.net/Tt3jk/7/For testing purposes I called a similar SendData2()function from within your first function's success event to simulate an ugly async request scenario. If you test this code on a real environment(or place the SendData2 with your url that responds with your data type which was "text" what you should see on the console is this output. (1- is console.log from SendData()and 2- is from SendData2()):

我将您的原始代码复制粘贴到小提琴上,并添加了我刚刚推荐的部分和一些日志。jsfiddle.net/Tt3jk/7/出于测试目的,我SendData2()从你的第一个函数的成功事件中调用了一个类似的函数来模拟一个丑陋的异步请求场景。如果您在真实环境中测试此代码(或将 SendData2 与您的 url 一起放置,该 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!

You can in fact even see it even on fiddle(with errors on the requests) when your reload function is being called. If you use "ajaxComplete", reload function inside your jQuery .click() function is being called quite early. However if you use "ajaxStop" and call reload function when "ajaxStop" event is triggered, reload function will be called after all the requests are completed.

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

I don't know if fiddle disappears after a while so I will post the changes I made here as well without console logs:

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

$(".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. Not sure if it's a good practice or not to make another request from within a request, probably not. But I put it there to show how "ajaxStop" event is delayed to be triggered until all ongoing requests are done(or completed with error at least)...

附注。不确定从请求中发出另一个请求是否是一个好习惯,可能不是。但我把它放在那里是为了展示“ajaxStop”事件是如何延迟触发的,直到所有正在进行的请求都完成(或至少有错误完成)......

回答by Jarek

it depends on way you do your requests For example (you don't do form submit. Otherwise you need prevent form submission)

这取决于您处理请求的方式例如(您不进行表单提交。否则您需要阻止表单提交)

$.ajax({
   url: 'some_url',
   type:    'GET',
   data: 'var1=value1&var2=value2',
 success: function(){
   //do smth
 },
 error: function(){
   alert(w.data_error);
   document.location.reload(); 
 }
 complete: function(){ //A function to be called when the request finishes (after success and error callbacks are executed) - from jquery docs
   //do smth if you need
   document.location.reload(); 
 }
});

Take a look onto complete block

查看完整的块

回答by Teoman shipahi

This would help;

这会有所帮助;

$("body").load("default.aspx");

Description: Load data from the server and place the returned HTML into the matched element. http://api.jquery.com/load/

描述:从服务器加载数据并将返回的 HTML 放入匹配的元素中。 http://api.jquery.com/load/