Created
October 2, 2010 06:41
-
-
Save sr3d/607378 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
/* Wrapper on top of the HTTP client */ | |
function Request(url, options) { | |
if( !url ) { throw "Invalid URL"; }; | |
options = _.extend({ | |
method: 'GET', | |
async: true, | |
evalJSON: true, | |
parameters: {}, | |
headers: [], // [ [key, value], [key, value] ] | |
onSuccess: function(){}, | |
onError: function(response){ log('Error Requesting'); log(response.responseText); } | |
}, options || {} ); | |
options.method = options.method.toUpperCase(); | |
if(!options.async) { showIndicator(); }; | |
/* construct the GET URL */ | |
if( options.method == 'GET' ) { | |
url = url + (/\?/.test(url) ? '' : '?') + toQueryString(options.parameters); | |
}; | |
log( options.method + ' ' + url + ' [' + toQueryString(options.parameters) + ']' ); | |
var request = Ti.Network.createHTTPClient(); | |
request.open(options.method, url, options.async); | |
request.timeout = 20000; // 20 seconds to timeout | |
request.onload = function() { | |
if(!options.async) { hideIndicator() }; // remove the indicator a bit | |
try { | |
// log(this.responseText); | |
if( options.evalJSON ) { | |
this.responseJSON = JSON.parse(this.responseText); | |
}; | |
options.onSuccess(this); // normalize to make it a bit more like Prototype | |
if(!options.async) { hideIndicator(); }; | |
} catch(ex) { | |
alert('Error parsing data'); | |
log(ex); | |
hideIndicator(); | |
}; | |
// this.release(); | |
}; | |
request.onerror = function() { | |
if(!options.async) { hideIndicator(); }; | |
options.onError(this); | |
}; | |
for(var i = 0; i < options.headers.length; i++ ) { | |
request.setRequestHeader(options.headers[i][0], options.headers[i][1]); | |
}; | |
if( options.method == 'GET' ) { | |
request.send(); | |
} else { | |
request.send(options.parameters); | |
}; | |
}; |
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
Request('http://localhost/test.js', { | |
evalJSON: false, | |
onSuccess: function(request) { | |
eval( '(function(){' + request.responseText + '})()'); | |
} | |
}); | |
// js file: | |
alert("I'm from the server"); | |
alert('another alert'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment