19.3.读取文本块(包括HTML和XML)

问题
我想读取文本块,如HTML或XML.
解决办法
使用URLLoader.load( )和DataFormat.TEXT
讨论
ActionScript 3.0 处理数据的方式已经和ActionScript 1.0 和2.0完全不同了,在以前的版本中,LoadVars 实例有两个不同的回调函数用于处理通过URL读取的数据。当处理读取的数据时触发onLoad( )回调函数,当数据读取完成时触发onData( )回调函数。

flash.net.URLLoader类和LoadVars类则不同,它只有一个complete事件和dataFormat属性用于决定如何解释这些下载的数据。dataFormat属性如果为DataFormat.TEXT,则会把数据解释为普通的文本内容,如果为DataFormat.VARIABLES则解释为URL-编码的变量,默认情况下,URLLoader把数据解释为文本。

假设从外部读取一个名为example.html的HTML数据,内容大致如下:
+展开
-HTML
<b>Title:</b> ActionScript 3.0 Cookbook<br >
<b>Authors:</b> Joey Lott, Darron Schall, Keith Peters<br >
<b>Publisher URL:</b> <a href="http://www.oreilly.com">www.oreilly.com</a>

下面的例子将读取并显示这些内容:
+展开
-ActionScript
package {
import flash.display.*;
import flash.text.*;
import flash.events.*
import flash.net.*;
public class HTMLLoadingExample extends Sprite {
private var _output:TextField;
public function HTMLLoadingExample( ) {
initializeOutput( );
loadData( );
}
private function initializeOutput( ):void {
_output = new TextField( );
_output.width = stage.stageWidth;
_output.height = stage.stageHeight;
_output.html = true// Enable HTML for the text field
addChild( _output );
}
private function loadData( ):void {
var loader:URLLoader = new URLLoader( );
// Instruct the loader to read the file as plain text - This line is not
// necessary because the dataFormat is DataFormat.TEXT by default.
loader.dataFormat = DataFormat.TEXT;
// Register an event handler for when the data is finished downloading
loader.addEventListener( Event.COMPLETE, handleComplete );
// Load the HTML text from the example.html file
loader.load( new URLRequest( "example.html" ) );
}
private function handleComplete( event:Event ):void {
var loader:URLLoader = URLLoader( event.target );
// Assign the htmlText of the text field to the HTML text that was contained
// in example.html. The data property of the URLLoader is the file contents.
_output.htmlText = loader.data;
}
}
}

data 属性的数据类型是根据dataFormat 属性的设置而决定的,如果设置为DataFormat.TEXT,则data 属性的值为String 类型,如果设置DataFormat.VARIABLES,则是Object 类型,如果设置为DataFormat.BINARY,则data 的数据类型为flash.util.ByteArray。

加支付宝好友偷能量挖...


评论(0)网络
阅读(98)喜欢(0)flash/flex/fcs/AIR