Re: Giving Javascript code access to Perl variables
Christopher Pryce <[email protected]>
| Newsgroups | gmane.comp.db.mysql.perl |
|---|---|
| Message-ID | <[email protected]> |
On Oct 17, 2005, at 5:27 PM, J Wermont wrote:
> I'll have to figure out a way to code it so that the
> subscript can be a Perl variable. Otherwise, there's no point to doing
> this, since I'd always have to know how many items were in the array,
> and how often does one know that?
you should take this off-list, as it way off topic.
the usual way to fill a javascript array is:
var ar = new Array();
ar[ ar.length ] = 'some value';
So, if you are creating your javascript from a Perl program, you can do
this (untested):
my $js = qq(<script type="text/javascript">
var ar = new Array();
);
foreach ( @somePerlList ) {
$js .= qq( ar[ ar.length ] = $_ );
}
$js .= qq(</script>);
You can do the same thing with a Perl hash and a javascript Array
(again, untested):
my $js = qq(<script type="text/javascript">
var ar = new Array();
);
while (($key, $value) = each %hash) {
$js = ar[ $key ] = $value;
}
Creates, in affect, an object.
You can combine a DBI fetch with a complex javascript object. Again,
untested:
my $sql = "Select * from foo":
my $sth = $dbh->prepare( $sql );
$sth->execute();
my $js = qq( var obj = new Object(); );
while (my $row = $sth->fecthrow_hashref() ) {
$js .= 'obj[ obj.length] = {' . join(", ", map{ "$_: $row->{ $_ }" }
keys %$row ) . "};\n";
}
or if you have a keyfield, in this example called 'rowid', you can do:
my $hashref = $dbh->selectall_hashref( $sql, 'rowid');
my $js = qq( var obj = new Object(); );
foreach my $rowid ( keys %$hashref ) {
$js .= "obj[ $rowid ] = {" . join(", ", map{ "$_: '$hashref->{ $rowid
}{ $_ }'" } keys %{ $hashref->{ $rowid } }) . "};\n";
}
and if you use the CGI module:
$script = script({-type=>'text/javascript'}, $js );
print header(), start_html(-head => $script ), etc...
--
MySQL Perl Mailing List
For list archives: http://lists.mysql.com/perl
To unsubscribe: http://lists.mysql.com/[email protected]