Skip to content

Instantly share code, notes, and snippets.

@rochapablo
Last active March 12, 2020 18:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rochapablo/7f174b2c2f10193fb79f5b8f7453191a to your computer and use it in GitHub Desktop.
Save rochapablo/7f174b2c2f10193fb79f5b8f7453191a to your computer and use it in GitHub Desktop.
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