ShowModalDialog
是一個用于顯示模態對話框(modal dialog)的 JavaScript 方法,通常用于在用戶執行某個操作之前顯示確認對話框、提示信息或其他需要用戶交互的內容。在 AJAX(Asynchronous JavaScript and XML)應用中,ShowModalDialog
可以用于在異步操作的不同階段與用戶進行交互。
以下是在 AJAX 應用中使用 ShowModalDialog
的一個簡單示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX ShowModalDialog Example</title>
<style>
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.4);
}
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
</style>
</head>
<body>
<button onclick="showModal()">Show Modal</button>
<div id="myModal" class="modal">
<div class="modal-content">
<p>Are you sure you want to proceed?</p>
<button onclick="confirmAction()">Yes</button>
<button onclick="closeModal()">No</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
script.js
的 JavaScript 文件,用于處理模態對話框的顯示和隱藏,以及 AJAX 請求:function showModal() {
var modal = document.getElementById('myModal');
modal.style.display = 'block';
}
function closeModal() {
var modal = document.getElementById('myModal');
modal.style.display = 'none';
}
function confirmAction() {
// Perform AJAX request
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// Handle the response data
var data = JSON.parse(xhr.responseText);
alert('Data received: ' + JSON.stringify(data));
}
};
xhr.send();
// Close the modal after performing the AJAX request
closeModal();
}
在這個示例中,當用戶點擊 “Show Modal” 按鈕時,將顯示一個模態對話框。用戶可以在其中選擇 “Yes” 或 “No”。如果用戶選擇 “Yes”,將執行一個 AJAX 請求以獲取數據。請求完成后,無論請求成功還是失敗,都將關閉模態對話框。