Here's a little snippet which can help... it takes any PHP variable
and translates it into its JavaScript equivalent. Taken from Drupal
(GPL license). The HTML-safe embedding of strings is there to avoid
problems when returning JSON through iframes, you probably won't need
that.
Also to avoid having to use templated JS, we have a transparent
mechanism for passing data from PHP to JS. All you do is call an API
drupal_add_js(), which aggregates all variables that it is passed,
and automatically inserts them as a single inline script tag in the
HTML head, as "Drupal.settings = { ... }". This works really well:
you don't need to dynamically generate .js files, and you avoid large
chunks of inline code.
/**
* Converts a PHP variable into its Javascript equivalent.
*
* We use HTML-safe strings, i.e. with <, > and & escaped.
*/
function drupal_to_js($var) {
switch (gettype($var)) {
case 'boolean':
return $var ? 'true' : 'false'; // Lowercase necessary!
case 'integer':
case 'double':
return $var;
case 'resource':
case 'string':
return '"'. str_replace(array("\r", "\n", "<", ">", "&"),
array('\r', '\n', '\x3c', '\x3e',
'\x26'),
addslashes($var)) .'"';
case 'array':
if (array_keys($var) === range(0, sizeof($var) - 1)) {
$output = array();
foreach ($var as $v) {
$output[] = drupal_to_js($v);
}
return '[ '. implode(', ', $output) .' ]';
}
// Fall through
case 'object':
$output = array();
foreach ($var as $k => $v) {
$output[] = drupal_to_js(strval($k)) .': '. drupal_to_js($v);
}
return '{ '. implode(', ', $output) .' }';
default:
return 'null';
}
}
Steven Wittens
_______________________________________________
jQuery mailing list
[email protected]
http://jquery.com/discuss/