I am noob in Flex/Actionscript so I have the code where compiler doesn’t show error but code returns nothing. Can you help me to fix it?
Main.mxml
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" creationComplete="main()">
<fx:Script>
<![CDATA[
include 'AS/main.as';
private function main():void {
Label1.text = Login('irakli','password1');
}
]]>
</fx:Script>
<s:Label id="Label1" x="370" y="176" text="Label"/>
</s:Application>
main.as
// ActionScript file
import flash.events.*;
import flash.net.*;
var Answer:String;
function Login(username:String, password:String){
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest('http://localhost/hosting/index.php');
request.method = URLRequestMethod.POST;
var variables:URLVariables = new URLVariables();
variables.username = username;
variables.password = password;
request.data = variables;
//handlers
loader.addEventListener(Event.COMPLETE, function(e:Event):void{
var loader:URLLoader = URLLoader(e.target);
Answer = loader.data;
});
loader.load(request);
var i:int = 1;
while (i < 10000000000){
if (Answer.length > 0){
return Answer;
break;
}
i++;
}
}
I know about that it is good to use event handler functions, but I want that this code worked in main.mxml Label1.text = Login('irakli','password1');
Sorry, but wanting this to work in this fashion is simply wrong. You have no guarantee that that absurd loop will work because it could easily complete before your load operation does. Also, having a function inline in your event handler is considered bad practice.
The correct approach to this would be to make Login a class, and listener for an event coming out of it in order to populate the text box.
This is how you could write Login as a class:
So then you would use this like this:
Of course if you don’t want listeners in your mxml (and I can’t understand why that would be), then I think your best approach would be to pass the target textField into your Login function and let it set the text in the inline handler. Something like:
main.as