Upload
aaron-crosman
View
1.489
Download
0
Embed Size (px)
Citation preview
Drupal Sins
How I learned to stop thinking and love sites
that bomb.
By: Aaron Crosman
The Goal
Allow an existing JavaScript app to get an
arbitrary node as JSON through an AJAX
callback.
The sinful solution
Create a custom response handler within
template.php that executes every time
template.php is loaded.
Better Solutions
All:
Views with a JSON display
Drupal 7:
https://www.drupal.org/project/contentasjson
Drupal 6:
Custom handler in template.php done right.
https://www.drupal.org/node/174008template.php
<?php
function _phptemplate_variables($hook, $vars) {
switch ($hook) {
case 'page':
// If the page was requested with the jQuery ajax functionalities, an HTTP header (X-Requested-
With: XMLHttpRequest)
// will be sent to the server, making it possible to identify if we should serve the content as
JSON
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 'XmlHttpRequest' ==
$_SERVER['HTTP_X_REQUESTED_WITH']) {
// Now that we know that the page was requested via remote scripting (AJAX) we can serve the
content as JSON
// by telling Drupal to use a different template for the page (in this case page-json.tpl.php)
$vars['template_files'] = is_array($vars['template_files']) ? $vars['template_files'] : array();
$vars['template_files'][] = 'page-json';
}
break;
}
}
?>
page-json.tpl.php
<?php
if($messages) {
$content = $messages.$content;
}
echo drupal_to_js($content);
?>
Just do it in views
https://www.drupal.org/project/views_datasource
Drupal 6 and 7, gives you a couple display
styles, including JSON.
You can output things any way views allows
not just dumping a node to JSON.
Create your view
Pick your fields and set the filter