Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Class: Ajax connectivity
- */
- // Default constructor
- function Ajax(_options) {
- // Set that reference
- var that = this;
- // Properties
- that.action = _options.action || undefined;
- that.method = _options.method || "GET";
- that.async = _options.async || true;
- that.params = _options.params || null;
- that.comet = _options.comet || false;
- that.success = _options.callback;
- that.error = _options.error;
- // Functions
- that.sanitizeToLastJson = function(_string) {
- return string.substring(_string.lastIndexOf("{"), _string.lastIndexOf("}")+1);
- }
- // Cancel if they omit this one
- if(typeof(that.action) === "undefined") {
- return false;
- }
- // Connect immediately
- try {
- that.request = new XMLHttpRequest() || new ActiveXObject("MSXML2.XMLHTTP.3.0");
- // Determine where get/post parameters go
- if(that.method === "GET" && that.params !== null) {
- that.request.open(that.method, that.action+"?"+encodeURI(that.params), that.async);
- }
- else {
- that.request.open(that.method, that.action, true);
- }
- // Set content header for json
- that.request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
- // Waiting for connect
- that.request.onreadystatechange = function() {
- // Using comet
- if(that.comet === true) {
- if(that.request.readyState === 3 && that.request.status === 200) {
- // If the success callback was set, call it
- if(typeof(that.success) !== "undefined") {
- that.success(that.sanitizeToLastJson(that.request.responseText));
- }
- }
- }
- // Success
- if(that.request.readyState === 4 && that.request.status === 200) {
- // If the success callback was set, call it
- if(typeof(that.success) !== "undefined") {
- that.success(that.request.responseText);
- }
- }
- }
- // Send the request differently if there is POST data
- if(that.method === "POST" && that.params !== null) {
- that.request.send(that.params);
- }
- else {
- that.request.send(null);
- }
- return true;
- }
- catch (e) {
- // Call the error callback if set
- if(typeof(that.error) !== "undefined") {
- that.error(e);
- }
- return false;
- }
- }
Add Comment
Please, Sign In to add comment