Search code examples
javascriptapex-codevisualforce

Returning array from apex controller class and using in javascript in Salesforce


I want to return an array from apex custom controller class in visualforce and use that array in JavaScript.

How I am doing:

Javascript:
   var SFObjectArray;
   function myJavascriptMethod()
   {
      SFObjectArray = myArrayItems();
   }


Apex:
<apex:actionFunction name="myArrayItems" 
                     action="{!myArrayItems}" 
                     status="mystatus" 
                     reRender="out"/>
</apex:actionFunction>

Controller:

public class MyController
{
  String[] arrayItems;

   public PageReference myArrayItems()
    {
       arrayItems = new String[]{'abc','def'};
        return null;
    }

    public String[] getItems()
     {
       return arrayItems ;
     }  
}

can anybody provide me some help.


Solution

  • You will have to dynamically build your javascript, the apex controller method will not return you a javascript object. I would use the visualforce repeat tag something like the following to build the javascript array.

    var SFObjectArray = new Array();
    <apex:repeat value="{!arrayItems}" var="arrayItem">
    SFObjectArray.push('{!arrayItem}');
    </apex:repeat>