Populate JavaScript array with results from apex methods
@Poet's answer handles most of the cases except where the StringOne
contains Single quotes in it.
If there is a single quote like StringOne='Lewi\'s'
it will break your Javascript execution, because it will render to
var myArray = ['Lewi's']
Better approach is:
var myArray = ['{!JSENCODE(StringOne)}', '{!JSENCODE(StringTwo)}'];
Suggestion:
If the object you want to render becomes bigger and complicated, I would recommend Serializing and Deserializing it as below:
public string getMyArrayContent() {
List<String> myArray = new List<String>();
myArray.add('StringOne');
.
.
myArray.Add('StringN');
return JSON.serialize(myArray);
}
In Javascript:
var myArray = JSON.parse('{!JSENCODE(myArrayContent)}');
The
JSENCODE
function encodes text strings and merge field values for use in JavaScript by inserting escape characters, such as a backslash(\)
, before unsafe JavaScript characters, such as the apostrophe(')
.
{!JSENCODE(text)}
and replace text with the merge field or text string that contains the unsafe JavaScript characters. So it not just prevents you from broken JS but also prevents XSS vulnerability if the string contains unsafe JavaScript code.
JSON.parse(str)
is a Javascript method which takes a String and converts it into Javascript object (Array here)
You should be able to simply do the following:
var myArray = ['{!StringOne}', '{!StringTwo}'];
Or
var myArray = [];
myArray.push({!StringOne});
myArray.push({!StringTwo});
Effectively because your two methods are just returning a String, you can just render them into the JS on your page and it'll work the same.