Created
February 3, 2013 15:45
-
-
Save egorvinogradov/4702227 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ajax(params){ | |
var request = new XMLHttpRequest(); | |
var responseTimer; | |
function handleError(e){ | |
console.error('Can\'t load data:', e.message, e); | |
params.error && params.error(e); | |
}; | |
request.open(params.method || 'GET', params.url, true); | |
request.onreadystatechange = function(){ | |
if ( request.readyState === 4 ) { | |
if ( request.status === 200 ) { | |
if ( params.success ) { | |
try { | |
var json = JSON.parse(request.responseText); | |
params.success(json); | |
} | |
catch(e){ | |
params.success(request.responseText); | |
} | |
} | |
} | |
else { | |
handleError({ | |
message: 'Bad request', | |
data: request | |
}); | |
} | |
clearTimeout(responseTimer); | |
} | |
}; | |
request.send(params.data || null); | |
responseTimer = setTimeout(function(){ | |
request.abort(); | |
handleError({ | |
message: 'Time is over' | |
}); | |
}, 10000); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment