开发者

i can't get variable in function

I can't read the variable in the function, I want to use it outside the function, here is m开发者_StackOverflow社区y code.

var contentLoader:URLLoader = new URLLoader();
contentLoader.load(new URLRequest("http://localhost/data.php"));

function onComplete(event:Event):void
{        

  var txtu:String = event.target.data;      

}
contentLoader.addEventListener(Event.COMPLETE, onComplete);

trace(txtu);

thanks.


basically you have a variable that is declared local to the function currently. you'll have to declare the variable outside of the function, where your contentLoader variable is defined and then assign the value in the function.


The issue here is that trace(txtu) is executed immediately after contentLoader.addEventListener(Event.COMPLETE, onComplete), which means it is occurring before the URLLoader is finished loading. So, there is nothing to trace in this situation because it hasn't been loaded yet.

Try calling another function at the end of onComplete(), which will ensure that the external data has fully loaded by that point.

For example:

var contentLoader:URLLoader = new URLLoader();
contentLoader.load(new URLRequest("http://localhost/data.php"));

function onComplete(event:Event):void 
{
  var txtu:String = event.target.data;
  continueWithProgram();
} 

contentLoader.addEventListener(Event.COMPLETE, onComplete);

function continueWithProgram():void
{
  trace(txtu);
}


you should be able to solve the problem by either passing the result into a new method like this:

var loaderResult: String;

var contentLoader:URLLoader = new URLLoader();
    contentLoader.addEventListener(Event.COMPLETE, onComplete);
    contentLoader.load(new URLRequest("http://localhost/data.php"));


// #option 1

function onComplete (event:Event): void {
    var txtu:String = event.target.data;
    continueWithProgram(txtu);
} 

function continueWithProgram (value:String): void {
  trace(txtu);
}

or use a variable outside of the event handler:

// #option 2

var loaderResult: String;

function onComplete (event:Event): void {
    loaderResult = event.target.data;
    continueWithProgram();
}

function continueWithProgram (): void {
  trace(loaderResult);
}

hope i could shed some light.. ;) regards.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜