Generating pages from a data source

Home

jQuery Mobile's loadPage method includes a filterResponseText option for filtering the data that is returned from the server after an page is loaded, before it is injected into the DOM. You can use this method to transform the server response in a variety of ways, whether it's replacing image paths, or implementing client-side templating system.

To use the filterResponseText option, simply define it as a function that has a single argument representing the raw Ajax response text, and that returns a string (presumably, that same data, modified in some way)


$.mobile.loadPage.defaults.filterResponseText = function( data ){
	return data.replace( "e", "EEEOOO" );
};

The following linked page is configured to return HTML or JSON, depending on whether it is requested through regular HTTP or Ajax.

View Dynamic Page

In the head of this page, the following script handles the templating for that page's JSON response


function myFakeTemplater( data, type ){
	
	// Dumb check to see if response is JSON
	if( data.indexOf( "{" === 0) ){
	
		//convert server JSON response to data
		var obj = $.parseJSON( data );

		//return string markup
		return '
' + '

' + obj.title + '

' + '
' + obj.content + '
' + '
'; } else { // Otherwise, return it, as it's probably HTML return data; } }; //set the loadPage default filter to run through myFakeTemplater $.mobile.loadPage.defaults.filterResponseText = myFakeTemplater;