Skip to content

Instantly share code, notes, and snippets.

@rochapablo

rochapablo/index.html

Last active Mar 12, 2020
Embed
What would you like to do?
after ajax request
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<meta name="author" content="">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<button type="button" onclick="callNextPage()">call next page</button>
<span id="page"></span>
<script src="jquery/dist/jquery.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>
var page = 1;
// Faz de conta que é uma lib
var AfterRequest = ((next, error) => {
var oldXHR = window.XMLHttpRequest;
function newXHR() {
var realXHR = new oldXHR();
realXHR.addEventListener("readystatechange", () => {
if (parseInt(realXHR.readyState, 0) === 4 && parseInt(realXHR.status, 0) === 200 && next) {
next();
} else if (error) {
error();
}
}, false);
return realXHR;
}
window.XMLHttpRequest = newXHR;
});
function init() {
$('#page').html(page);
}
function callNextPage() {
$.ajax({
type: 'GET',
url: `https://reqres.in/api/users?page=${page}`,
success: function (res) {
console.log(res);
page += 1;
$('#page').html(page);
}
});
}
init();
// Assim para chamar nossa lib
AfterRequest(() => {
// a cada request com sucesso cai aqui
console.log('good');
}, () => {
// a cada request direfente de sucesso, cai aqui
console.log('good with error');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment