jquery ajax后刷新页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18131542/
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 21:04:40  来源:igfitidea点击:

refresh page after jquery ajax

javascriptjqueryajaxrefresh

提问by jaynp

I am trying to refresh the page after a jQuery AJAX call. It appears that the page is refreshing (only sometimes) before all the data has been transmitted. Can anyone see why by this snippet below. I have the refresh code in the success function so I am confused.

我试图在 jQuery AJAX 调用后刷新页面。在传输所有数据之前,页面似乎正在刷新(仅有时)。任何人都可以通过下面的这个片段看出原因。我在成功函数中有刷新代码,所以我很困惑。

I tried adding async = falseand that didn't seem to work either.

我尝试添加async = false,但似乎也不起作用。

function sendRating(rating, reload_on_return) {

$.ajax({
    type: "POST",
    dataType: 'json',
    url: window.url_root + cid + "/",
    data: {
        "rating": rating.r2 / 100.0
    },
    success: function(data) {
        if (data.hasOwnProperty('success')) {
            console.log("data was sent!");

            if (reload_on_return) {
                    location.reload();

            }

        }
    },
    error: function() {
        console.log("Data didn't get sent!!");
    }
})

回答by broguyman

You could possibly do a setTimeout, to make it wait for a split second before the refresh can execute.

您可能会执行 setTimeout,使其在执行刷新之前等待一秒钟。

function sendRating(rating, reload_on_return) {

$.ajax({
    type: "POST",
    dataType: 'json',
    url: window.url_root + cid + "/",
    async: false,
    data: {
        "rating": rating.r2 / 100.0
    },
    success: function(data) {
        if (data.hasOwnProperty('success')) {
            console.log("data was sent!");

            if (reload_on_return) {
                setTimeout(
                  function() 
                  {
                     location.reload();
                  }, 0001);    
            }

        }
    },
    error: function() {
        console.log("Data didn't get sent!!");
    }
})