Send array from script include to client script.

anand98900
Kilo Contributor

I am trying to send array from script include to client script and traverse that array.

But i am unable to get an array in client script.

1 ACCEPTED SOLUTION

Chuck Tomasi
Tera Patron

You need to encode your array in the script include and return a JSON string.



// Helsinki


return JSON.stringify(arrayName);



// Pre-Helinki


return new JSON().encode(arrayName);



In your client script, you parse the answer from the response like you normally would, but when you extract your array from the answer like this



var myArray = answer.evalJSON();



Docs: Client Scripts


Docs: GlideForm


Docs: GlideAjax


Client Script Best Practices - ServiceNow Wiki      


View solution in original post

8 REPLIES 8

Chuck Tomasi
Tera Patron

You need to encode your array in the script include and return a JSON string.



// Helsinki


return JSON.stringify(arrayName);



// Pre-Helinki


return new JSON().encode(arrayName);



In your client script, you parse the answer from the response like you normally would, but when you extract your array from the answer like this



var myArray = answer.evalJSON();



Docs: Client Scripts


Docs: GlideForm


Docs: GlideAjax


Client Script Best Practices - ServiceNow Wiki      


Thank you Chuck.



For the shake of information if try to send this object from script include to client script                          



var sendResponse = '{role:[{"id": "123", "name": "IT_Role"},{"id": "456", "name": "BUSINESS_Role", }]}';


var responseJONObject = new global.JSON().decode(sendResponse)



How do i send this responseJSONObject object to client script and get name from this objects.




Replace decode with encode on line 2. You are turning the object in to a string.


Abhinay Erra
Giga Sage

Post you code here. I can edit your code