jQuery AJAX request demo
HTML
<div id="overlay">
<div id="overlay_mask">載入中,請稍後...</div>
</div>
<a href="#" onclick="return getSuccessOutput();"> test success </a> | <a href="#" onclick="return getFailOutput(); return false;"> test failure</a>
<div id="output">waiting for action</div>
CSS
#overlay{
width: 0%;
height: 100%;
display: none;
position: fixed;
top:0px;
left:0px;
transition: all .3s;
overflow: hidden;
}
#overlay_mask{
width: 100vw;
height: 100%;
font-size: 6em;
background: rgba(0,0,0,0.6);
display:flex;
align-items:center;
justify-content:center;
/* display:none; */
}
a {
padding: 0.2em;
}
a:hover {
background-color: #02AAEE;
}
#output {
display: block;
margin-top: 8px;
padding: 1%;
border: 1px solid #666;
background-color: #efefef;
}
JavaScript
$(document).on('ajaxSend',function(){
$('#overlay').show();
$('#overlay').width('100%');
$(window).on('beforeunload',function(){
if( confirm('查詢未完成,是否要離開?')){
return true;
}
return false;
});
}).on('ajaxComplete',function(){
$('#overlay').width('0px');
$(window).off('beforeunload');
})
;
// handles the click event, sends the query
function getSuccessOutput() {
$.ajax({
url:'/echo/js/?js=hello%20world!',
complete: function (response) {
$('#output').html(response.responseText);
},
error: function () {
$('#output').html('Bummer: there was an error!');
},
});
return false;
}
// handles the click event, sends the query
function getFailOutput() {
$.ajax({
url:'myAjax.php',
success: function (response) {
console.log(data, response);
$('#output').html(response);
},
error: function () {
$('#output').html('Bummer: there was an error!');
},
});
return false;
}