提交后Alert弹窗未显示,如何实现弹窗等待用户确认后再跳转?
问题描述
我编写了如下代码,意图提示用户问题已提交后刷新页面:
protected void ButtonSubmitQuestionClick(object sender, EventArgs e) { -- A whole bunch of code that does stuff -- //close window ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alert", "alert('Your question has been submitted!');window.close();", true); Response.Redirect("~/QA_QuestionIntake.aspx"); }
实际运行时弹窗从未出现,推测是页面被立即刷新导致的。请问怎么让代码在Alert弹窗处暂停,等用户点击确认后再执行后续操作?
解决方法
问题根源是Response.Redirect会立刻给客户端发送跳转指令,浏览器还没来得及执行你注册的弹窗脚本就直接跳转了。要实现弹窗确认后再执行后续操作,得把跳转/关闭窗口的逻辑放到前端脚本里,同时删掉后端的Response.Redirect。
方案1:弹窗确认后跳转页面
修改后的代码如下:
protected void ButtonSubmitQuestionClick(object sender, EventArgs e) { -- A whole bunch of code that does stuff -- // 将跳转逻辑整合到前端脚本中,用ResolveUrl确保路径解析正确 string script = "alert('Your question has been submitted!'); window.location.href = '" + ResolveUrl("~/QA_QuestionIntake.aspx") + "';"; ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alertAndRedirect", script, true); // 务必移除Response.Redirect,否则脚本无法执行 }
方案2:弹窗确认后关闭窗口
如果你的需求是关闭当前窗口而非跳转,代码可以改成这样:
protected void ButtonSubmitQuestionClick(object sender, EventArgs e) { -- A whole bunch of code that does stuff -- string script = "alert('Your question has been submitted!'); window.close();"; ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alertAndClose", script, true); }
原理说明
后端通过ScriptManager.RegisterStartupScript注册的脚本,会在页面加载完成后执行。alert弹窗会阻塞浏览器的脚本执行流程,直到用户点击确认按钮,之后才会执行后面的跳转或关闭窗口操作。而Response.Redirect会直接终止当前页面的输出,触发浏览器立即跳转,所以必须移除它才能让前端脚本正常运行。
内容的提问来源于stack exchange,提问作者Johnny Bones
相关产品推荐
相关产品推荐

