如何处理 AJAX 确认对话框的"是"或"否"



在belwo代码中,当用户访问以下URL时,我正在尝试创建ajax调用,如下所示:

"/product/remove/" + idx,

我想显示一个带有"是"和"否"的对话框,并且只有在用户输入上一个 url 并单击 Enter 时,以及在执行处理删除或删除操作的控制器的逻辑之前,此对话框才应该出现,这就是为什么我在下面的 $.ajax 调用中使用"beforeSend"属性。

我在谷歌上搜索了几篇关于如何使用ajax call和spring MVC集成和创建确认对话框的帖子,但是我得到的大多数点击都需要进一步澄清。

我想要实现的是,当用户单击"是"时,代码中显示的控制器 belwo 应该正常执行。 当用户单击"否"时,不应发生任何操作,只有对话框 应该消失。

请在下面找到我的尝试,请帮助我实现它

code_1

@<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Ajax confirm delete prodcut</title>
<script
src="${pageContext.request.contextPath }/resources/js/jquery-1.6.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {

$('#confirmremoveform').click(function() {
var idx = $('#idx').val();
var ans = confirm("Are you sure you want to delete this Record?");
if (ans) {
$.ajax({
type: "DELETE",
url: "/product/remove/" + idx,
dataType : 'json',
contentType : 'application/json',
beforeSend: function () {
$("#modal-book").modal("show");
},
success: function (data) {
$("#modal-book .modal-content").html(data.html_form);
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
});
}
</script>
</head>
<body>
<fieldset>
<legend>confirmremove</legend>
<input type="button" value="confirmremove" id="confirmremoveform" />
<br/>
<span id="result0"></span>
</fieldset>
</body>
</html>

控制器

@Controller
@RequestMapping("/product/remove")
public class RemoveProductPageController {
public final static String sRemoveProductFromListAttributeName = "removeProductFromList";
public final static String CONTROLLER_URL = "/product/remove";
public final static String DO_REMOVE_HANDLER_METHOD_URL = CONTROLLER_URL + "/{idx}";
@Autowired
private ProductService productService;
@RequestMapping(value = "/{idx}", 
method = RequestMethod.DELETE)
@ResponseBody
public ResponseEntity<String> doRemove(@Validated @Size(min = 0) @PathVariable(required = true) int idx,
Model model) {
Product productToBeRemove = productService.getProductFromListByIdx(idx);
if (productToBeRemove == null) {
return new ResponseEntity<String>("no product is avaialble at index:" + idx, HttpStatus.NOT_FOUND);
}
model.addAttribute(RemoveProductPageController.sRemoveProductFromListAttributeName, productToBeRemove);
productService.removeProdcutFromListBxIdx(idx);
return new ResponseEntity<String>("product removed from index: " + idx, HttpStatus.OK);
}
}

替换以下逻辑

var ans = confirm("Are you sure you want to delete this Record?");
if (ans) {
//your all code
}
// with a single liner
if (confirm("Are you sure you want to delete this Record?")) {}

最新更新