Perl Requires Chilkat v11.4.0+
Chilkat2 Perl
Call a JavaScript Function Returning a String
See more JavaScript Examples
Demonstrates how to call a JavaScript function that returns a string.Chilkat Perl Downloads
use strict;
use warnings;
use Chilkat2;
# This is the JavaScript function we'll call:
# function greet(name) {
# return "Hello, " + name + "!";
# }
my $sbScript = Chilkat2::StringBuilder->new;
$sbScript->Append('function greet(name) { return "Hello, " + name + "!"; }');
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 greet("Michael")
my $funcCall = Chilkat2::JsonObject->new;
# Create JSON specifying the function name and arguments
# {
# "name": "greet",
# "args": [ "Michael" ]
# }
$funcCall->UpdateString('name', 'greet');
$funcCall->UpdateString('args[0]', 'Michael');
$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": "string",
# "value": "Hello, Michael!"
# }
my $retval = $result->StringOf('value');
print $retval, "\n";
# Output:
# Hello, Michael!