2016-11-30 37 views
2

警告我有一个按钮:防止 '确认导航' 与window.location.href

<button type="button" class="btn btn-primary mt15 send-emails" name="SendEmails" value="true">Send Emails</button> 

与方法:

$('.send-emails').click(function (e) { 
     // build data and other stuff 
     $.post('/leads/sendemails', data, function (data, status, xhr) { 
      alert('Emails have successfully been queued for sending.'); 
      window.onbeforeunload = null; 
      window.location.href = '/Leads/Lead/' + @Model.LeadID; 
    }, 'json'); 
}); 

即使window.onbeforeunload = null;我仍然得到弹出警告:

enter image description here

我如何避免这种情况?

+0

请试试这个:'$(window).unbind();' –

+0

工作正常!列出它作为答案? –

回答

1

该解决方案如下:

$(window).unbind(); 

这将删除onbeforeunload事件只是浏览器之前重定向到一个新的页面使用location.href

+0

这不能解决我的问题。 :( 是否有任何其他解决方案此问题?? – M05

+0

这对我起初工作,然后没有工作后,我解决了这个问题,通过设置'onbeforeundload = function(){}' – Femtosecond

+0

@Femtosecond,你可以添加这是为了帮助其他人的答案。 –

0

使用全局变量在重定向到像这样的页面之前进行检查。有一个字符串变量来保存href您需要重定向和语句之前重定向它

(function($){ 
    var dontSubmit = false, 
     $form = $('form#my-form'); 

    // Prevent the trigger a false submission on link click 
    window.addEventListener("beforeunload", function (e) { 
     dontSubmit = true; 
     $form.trigger('submit'); 
    }); 

    $form.on('submit', function(event){ 
     if (dontSubmit) { 
      event.preventDefault(); 
      return; 
     } 

     // Continue on as normal 
    }); 
})(jQuery);