Perl Requires Chilkat v11.4.0+
Chilkat2 Perl
Call a JavaScript Function Returning an Object
See more JavaScript Examples
Demonstrates how to call a JavaScript function that returns an object.Chilkat Perl Downloads
use strict;
use warnings;
use Chilkat2;
# This is the JavaScript function we'll call:
# function getSettings() {
# return {
# theme: "dark",
# notifications: true,
# version: 1.0
# };
# }
my $sbScript = Chilkat2::StringBuilder->new;
$sbScript->Append('function getSettings() {');
$sbScript->Append(' return {');
$sbScript->Append(' theme: "dark",');
$sbScript->Append(' notifications: true,');
$sbScript->Append(' version: 1.0');
$sbScript->Append(' };');
$sbScript->Append('}');
my $js = Chilkat2::Js->new;
my $result = Chilkat2::JsonObject->new;
$result->EmitCompact(0);
# Call Eval to add the function to the context's global object
my $success = $js->Eval($sbScript, $result);
if (!$success) {
# Examine the result for an exception.
print $result->Emit(), "\n";
# Also examine the LastErrorText.
print $js->LastErrorText, "\n";
exit;
}
# ------------------------------------------------------------------------------
# Call the function getSettings()
my $funcCall = Chilkat2::JsonObject->new;
# Create JSON specifying the function name and arguments
# The function has no arguments, so we only specify the name.
# {
# "name": "getSettings",
# }
$funcCall->UpdateString('name', 'getSettings');
$success = $js->CallFunction($funcCall, $result);
if (!$success) {
# Examine the result for an exception.
print $result->Emit(), "\n";
# Also examine the LastErrorText.
print $js->LastErrorText, "\n";
exit;
}
print $result->Emit(), "\n";
# Output:
# {
# "type": "object",
# "value": {
# "theme": "dark",
# "notifications": true,
# "version": 1
# }
# }
# Examine the object's members
print 'theme: ', $result->StringOf('value.theme'), "\n";
print 'notifications: ', ($result->BoolOf('value.notifications') ? 1 : 0), "\n";
print 'version: ', $result->IntOf('value.version'), "\n";
# Output:
# theme: dark
# notifications: True
# version: 1