Skip to content
This repository was archived by the owner on Jan 19, 2019. It is now read-only.

HTTP Client

wGEric edited this page Oct 5, 2011 · 1 revision

Creates an HTTP client to get data from a remote server. This is similar to AJAX in the browser.

$.http

The http method has one parameter which is an object of settings. The available settings are:

  • url (where to send the request)
  • type (get or post)
  • data (the data to send in the request)
  • dataType (type of data that will be received. XML, JSON or blank for anything else)
  • Timeout (milliseconds before the connection to timesout)
  • headers (object of additional headers to set in the request)
  • onError (callback if there is an error)
  • onLoad (callback when the connection is complete)

The http method will return the parsed XML or JSON or the text that is received from the request. This is determined by the dataType setting.

Titanium

var http = Titanium.Network.createHTTPClient();
http.setTimeout(3000);

http.onload = function() {
	// xml
	var data = this.responseXML;

	// JSON
	var data = JSON.parse(this.responseText);

	// other
	var data = this.responseText;

	// do something with data
};

http.onerror = function(event) {
	Titanium.API.error('http error: ' + event.error);
};

http.open('get', 'http://www.google.com');

http.send();

TiQuery

$.http({
	url: 'http://www.google.com',
	onLoad: function(data, http, event) {
		// do something with data
	}
});

TiQuery will log errors to the console for you so you don't need to add an onError callback.

Shortcuts

TiQuery provides shortcuts to to the http method for common requests. For example:

$.get('http://www.google.com', function(data) {
	// do something with data
});

$.getJSON('http://www.google.com', {'field1': 'value1', 'field2':'value2'}, function(data) {
	// do something with data
});

$.getXML('http://www.google.com', function(data) {
	// do something with data
}, {'extra': 'headers'});

Replace get with post to do post requests. The syntax is:

$.get(url, data, callback, headers);

Clone this wiki locally