0

I want to call a method in flex from javascript side,

so that I can retrieve javascript object which contains data in flex.

now I'm trying like

var result:Object = new Object()
var keyset:Array = data.getKeySet();

for (var i:int = 0 ; i < keyset.length ; i++) {
    result[keyset[i]] = data.get(keyset[i]);
}

return result;

but it do not work. how can I make it right?

p.s. I know it is fundamental question, but I couldn't find anything even though I googled for an hour. So please help!

2 Answers 2

2

To communicate between Flash/Flex and JS on the page, use the ExternalInterface class. You can't directly pass objects, but you can convert your object into a serialisable/string. Here's how you'd call a function called 'myFunc' and set it two arguments, a string and a number:

ExternalInterface.call('myFunc',1,'aString');

After the function name, which must always be a string, there is a ...rest parameter. Simply enough, this means you can send any number of arguments to the function, separating them with commas (we do two here).

If you used AS2 at any point in the past you may know the 'eval' function, this was inherited from (and is thus still used by) JS - it analyses a string and attempts to parse it into JavaScript, using this you can literally send Javascript code instead of a func/args:

ExternalInterface.call('alert("Hello!")');

If you want two-way communication, use the ExternalInterface.addCallBack function to register a function as callable from JS.

In case of errors when doing this, you may need to adjust your embed code: "In the object tag for the SWF file in the containing HTML page, set the following parameter:

param name="allowScriptAccess" value="always"

Sign up to request clarification or add additional context in comments.

Comments

0

I believe you cannot call a method in AS3 from JS directly (and vice-versa). There should be an interface for it though, where one can call the other. If i remember correctly, you should use the ExternalInterface API.

Also, you can't pass Flex objects to JS (and vice-versa) also. Try building a generic object that is serializable to JSON and use that serialized data in passing data to each other. The receiving party can parse it back to use the data. In this example, the code passed a string from JS to AS3.

In your case, the Flex function would:

  • build an object
  • stuff it with data
  • serialize it into a JSON string
  • return the string to the caller

Then when JS calls the function:

  • JS receives the string
  • Use JSON.parse() to reconstruct the JSON string into a JS object
  • use the object

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.