Skip to content

Instantly share code, notes, and snippets.

@sr3d
Created October 2, 2010 06:41
Show Gist options
  • Save sr3d/607378 to your computer and use it in GitHub Desktop.
Save sr3d/607378 to your computer and use it in GitHub Desktop.
/* 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);
};
};
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