JavaScript确认框总是返回true。

3

这是我的确认框代码。当我点击 确定 时,它应该调用删除函数。当我点击 取消 时,它应该返回主页,但即使我选择了取消,文件也被删除了。这是我的代码。问题出在哪里?

var response = confirm ("Are you sure you want to permanently delete this user?");  

if (response)  
{  
  <% String userName =request.getParameter("userName");      
     del.del(userName);
   %> 
  window.location.href='adminHome.jsp';
}
else
{
  window.location.href='adminHome.jsp'; 
}
1个回答

5
这段代码:
<% String userName =request.getParameter("userName");
del.del(userName);%>

在页面发送到浏览器之前,服务器上运行,因此用户在您甚至执行 confirm() 之前就已经离开了。

您需要引入一个明确的新HTTP请求,可以通过简单地发布表单或通过ajax来处理,并在服务器上处理该请求。只有当您的确认返回 true 时,才会触发该请求。


我不知道如何使用Ajax请求,你能给我一个例子吗? - nallas
@nallas 嗯,这是一个大话题;幸运的是,网上有很多教程可供参考。 - Pointy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接