![]() |
Chilkat HOME Android™ AutoIt C C# C++ Chilkat2-Python CkPython Classic ASP DataFlex Delphi DLL Go Java JavaScript Node.js Objective-C PHP Extension Perl PowerBuilder PowerShell PureBasic Ruby SQL Server Swift Tcl Unicode C Unicode C++ VB.NET VBScript Visual Basic 6.0 Visual FoxPro Xojo Plugin
(PureBasic) Call a JavaScript Function Returning a StringSee more JavaScript ExamplesDemonstrates how to call a JavaScript function that returns a string.Note: This example requires Chilkat v11.4.0 or greater.
IncludeFile "CkJs.pb" IncludeFile "CkStringBuilder.pb" IncludeFile "CkJsonObject.pb" Procedure ChilkatExample() success.i = 0 ; This is the JavaScript function we'll call: ; function greet(name) { ; return "Hello, " + name + "!"; ; } sbScript.i = CkStringBuilder::ckCreate() If sbScript.i = 0 Debug "Failed to create object." ProcedureReturn EndIf CkStringBuilder::ckAppend(sbScript,"function greet(name) { return " + Chr(34) + "Hello, " + Chr(34) + " + name + " + Chr(34) + "!" + Chr(34) + "; }") js.i = CkJs::ckCreate() If js.i = 0 Debug "Failed to create object." ProcedureReturn EndIf result.i = CkJsonObject::ckCreate() If result.i = 0 Debug "Failed to create object." ProcedureReturn EndIf CkJsonObject::setCkEmitCompact(result, 0) ; Call Eval to add the function to the context's global object success = CkJs::ckEval(js,sbScript,result) If success = 0 ; Examine the result for an exception. Debug CkJsonObject::ckEmit(result) ; Also examine the LastErrorText. Debug CkJs::ckLastErrorText(js) CkStringBuilder::ckDispose(sbScript) CkJs::ckDispose(js) CkJsonObject::ckDispose(result) ProcedureReturn EndIf ; ------------------------------------------------------------------------------ ; Call the function greet("Michael") funcCall.i = CkJsonObject::ckCreate() If funcCall.i = 0 Debug "Failed to create object." ProcedureReturn EndIf ; Create JSON specifying the function name and arguments ; { ; "name": "greet", ; "args": [ "Michael" ] ; } CkJsonObject::ckUpdateString(funcCall,"name","greet") CkJsonObject::ckUpdateString(funcCall,"args[0]","Michael") success = CkJs::ckCallFunction(js,funcCall,result) If success = 0 ; Examine the result for an exception. Debug CkJsonObject::ckEmit(result) ; Also examine the LastErrorText. Debug CkJs::ckLastErrorText(js) CkStringBuilder::ckDispose(sbScript) CkJs::ckDispose(js) CkJsonObject::ckDispose(result) CkJsonObject::ckDispose(funcCall) ProcedureReturn EndIf Debug CkJsonObject::ckEmit(result) ; Output: ; { ; "type": "string", ; "value": "Hello, Michael!" ; } retval.s = CkJsonObject::ckStringOf(result,"value") Debug retval ; Output: ; Hello, Michael! CkStringBuilder::ckDispose(sbScript) CkJs::ckDispose(js) CkJsonObject::ckDispose(result) CkJsonObject::ckDispose(funcCall) ProcedureReturn EndProcedure |
||||
© 2000-2026 Chilkat Software, Inc. All Rights Reserved.