简体   繁体   English

Javascript - 仅在效果完成后重新加载页面

[英]Javascript - Reload page only after the effect are finished

I have this code - after I click a button, the spell function will run, which should play a short sound and show/hide some image, after that it executes some database queries via ajax in PHP and then refreshes the current page via window.location: I have this code - after I click a button, the spell function will run, which should play a short sound and show/hide some image, after that it executes some database queries via ajax in PHP and then refreshes the current page via window.地点:

function spell(val,val1,val2) {

if (val === 1) {
    let magic ='<img src="effects/thunder.png" alt="thunder"/>';
    document.getElementById('thunder').play();
    $("#effect").html(magic).show().delay( 200 ).fadeOut(200);}

if (val === 2) {...}

    $.ajax
    ({url: 'spell.php',
        data: {"var1": val,"var2": val1,"var3": val2},
        type: 'get',
        success: function(json) {
             if(!json.error) window.location="game.php";
    }});

}

If I remove the window.location, then it works fine, sound is played, image is showed.如果我删除 window.location,那么它工作正常,播放声音,显示图像。

But the ajax execution and window location doesn't wait until the sound and jquery effects are finished, and it refreshes the page so quickly, that no sound is played and no image is shown.但是 ajax 执行和 window 位置没有等到声音和 jquery 效果完成,它刷新页面这么快,没有播放和显示图像声音。

How can I achieve that the window location will wait to finish the effects?如何实现 window 位置将等待完成效果?

I'd recommend adding a callback function to your fadeOut function if you want the ajax to wait for it.如果您希望 ajax 等待它,我建议您将回调 function 添加到您的淡出 function 中。

function spell(val,val1,val2) {
  if (val === 1) {
    let magic ='<img src="effects/thunder.png" alt="thunder"/>';
    document.getElementById('thunder').play();
    $("#effect").html(magic).show().delay( 200 ).fadeOut(200, function() {
      //we're ready to start the game
      startGame(val, val1, val2);
    });
  }
}

function startGame(val, val1, val2) {
  $.ajax({url: 'spell.php',
    data: {"var1": val,"var2": val1,"var3": val2},
    type: 'get',
    success: function(json) {
      if(!json.error) window.location="game.php";
    }
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM