Xbase++ Requires Chilkat v11.4.0+
Xbase++
Call a JavaScript Function Returning a String
See more JavaScript Examples
Demonstrates how to call a JavaScript function that returns a string.Chilkat Xbase++ Downloads
LOCAL nSuccess
LOCAL oSbScript
LOCAL oJs
LOCAL oResult
LOCAL oFuncCall
LOCAL cRetval
nSuccess := 0
// This is the JavaScript function we'll call:
// function greet(name) {
// return "Hello, " + name + "!";
// }
oSbScript := CreateObject("Chilkat.StringBuilder")
oSbScript:Append('function greet(name) { return "Hello, " + name + "!"; }')
oJs := CreateObject("Chilkat.Js")
oResult := CreateObject("Chilkat.JsonObject")
oResult:EmitCompact := 0
// Call Eval to add the function to the context's global object
nSuccess := oJs:Eval(oSbScript, oResult)
IF (nSuccess == 0)
// Examine the result for an exception.
? oResult:Emit()
// Also examine the LastErrorText.
? oJs:LastErrorText
oSbScript:destroy()
oJs:destroy()
oResult:destroy()
RETURN
ENDIF
// ------------------------------------------------------------------------------
// Call the function greet("Michael")
oFuncCall := CreateObject("Chilkat.JsonObject")
// Create JSON specifying the function name and arguments
// {
// "name": "greet",
// "args": [ "Michael" ]
// }
oFuncCall:UpdateString("name", "greet")
oFuncCall:UpdateString("args[0]", "Michael")
nSuccess := oJs:CallFunction(oFuncCall, oResult)
IF (nSuccess == 0)
// Examine the result for an exception.
? oResult:Emit()
// Also examine the LastErrorText.
? oJs:LastErrorText
oSbScript:destroy()
oJs:destroy()
oResult:destroy()
oFuncCall:destroy()
RETURN
ENDIF
? oResult:Emit()
// Output:
// {
// "type": "string",
// "value": "Hello, Michael!"
// }
cRetval := oResult:StringOf("value")
? cRetval
// Output:
// Hello, Michael!
oSbScript:destroy()
oJs:destroy()
oResult:destroy()
oFuncCall:destroy()