C++
C++
Call a JavaScript Function Returning a String
See more JavaScript Examples
Demonstrates how to call a JavaScript function that returns a string.Chilkat C++ Downloads
#include <CkStringBuilder.h>
#include <CkJs.h>
#include <CkJsonObject.h>
void ChilkatSample(void)
{
bool success = false;
// This is the JavaScript function we'll call:
// function greet(name) {
// return "Hello, " + name + "!";
// }
CkStringBuilder sbScript;
sbScript.Append("function greet(name) { return \"Hello, \" + name + \"!\"; }");
CkJs js;
CkJsonObject result;
result.put_EmitCompact(false);
// Call Eval to add the function to the context's global object
success = js.Eval(sbScript,result);
if (success == false) {
// Examine the result for an exception.
std::cout << result.emit() << "\r\n";
// Also examine the LastErrorText.
std::cout << js.lastErrorText() << "\r\n";
return;
}
// ------------------------------------------------------------------------------
// Call the function greet("Michael")
CkJsonObject funcCall;
// 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 == false) {
// Examine the result for an exception.
std::cout << result.emit() << "\r\n";
// Also examine the LastErrorText.
std::cout << js.lastErrorText() << "\r\n";
return;
}
std::cout << result.emit() << "\r\n";
// Output:
// {
// "type": "string",
// "value": "Hello, Michael!"
// }
const char *retval = result.stringOf("value");
std::cout << retval << "\r\n";
// Output:
// Hello, Michael!
}