您好,欢迎访问一九零五行业门户网

用仿ActionScript的语法来编写html5——第九篇,仿URLLoader读取文件

第九篇,仿urlloader读取文件
先看看最后的代码
function readfile(){ urlloader = new lurlloader(); urlloader.addeventlistener(levent.complete,readfileok); urlloader.load("../file/test.txt","text"); } function readfileok(){ mytxt.text = urlloader.data; }
基本上已经实现了actionscript的模仿了。
效果和代码看这里,看不到效果的请下载支持html5的浏览器
http://fsanguo.comoj.com/html5/jstoas09/index.html
下面说说实现过程
其实javascript中的activexobject是可以实现本地文件的读写的,但是你的浏览器的安全级别必须设定到最低,但是我们做的游戏和网页是要放到网上的,我们没有办法要求所有的用户这样做。
在这里,我用php来实现这一过程,php可以自由读取服务器上的文件,它并不依赖用户的浏览器的设定
用php读取文件很简单,一个fopen函数就可以搞定,下面是file.php的代码
if(!file_exists($_post["file"])){ echo ""; exit; } $file = fopen($_post["file"],"r"); $filemsg = ""; while (!feof($file)) { $line = fgets($file); $filemsg = $line; } fclose($file); echo $filemsg;
把这个php放到你喜欢的位置,然后在legend.js里面设定路径legend_file_php指向你放的位置
关于javascript调用php,当然可以自己写,因为它并不算复杂,但是我是一个很懒的人,所以我直接用jquery来调用了,jquery是什么?估计不用我解释了吧
关于lurlloader的构造,和lloader基本一样,只有load方法不一样,下面是lurlloader类的完整代码,里面调用了之前准备的php来获取要读取的文本
function lurlloader(){ var self = this; self.objectindex = ++lglobal.objectindex; self.type="lurlloader"; self.loadtype = ""; self.content = null; self.oncomplete = null; self.event = {}; } lurlloader.prototype = { addeventlistener:function(type,listener){ var self = this; if(type == levent.complete){ self.oncomplete = listener; } }, load:function (path,loadtype){ var self = this; self.loadtype = loadtype; if(self.loadtype == "text"){ $.post(legend_file_php, { flg:"read", file:path },function(data){ if(self.oncomplete){ self.event.currenttarget = data; self.data = data; self.oncomplete(self.event); } }); } } }
关于上面的例子,我加了一个按钮,一个ltextfield,代码看下面
init(40,"mylegend",600,500,main); var loadinglayer; var backlayer; var urlloader var mytxt; function main(){ legendloadover(); var readbtn = addbutton("读取",20); readbtn.x = 10; readbtn.y = 20; addchild(readbtn); readbtn.addeventlistener(lmouseevent.mouse_down, readfile); mytxt = new ltextfield(); mytxt.x = 10; mytxt.y = 50; mytxt.text = ""; mytxt.width = 300; mytxt.height = 200; mytxt.settype(ltextfieldtype.input); addchild(mytxt); } function readfileok(){ mytxt.text = urlloader.data; } function readfile(){ urlloader = new lurlloader(); urlloader.addeventlistener(levent.complete,readfileok); urlloader.load("../file/test.txt","text"); } function addbutton(lbl,x){ var up = new lsprite(); up.graphics.drawrect(1,"black",[0, 0, 80, 20],true,"#999999"); var txt = new ltextfield(); txt.x = x; txt.text = lbl; up.addchild(txt); var over = new lsprite(); over.graphics.drawrect(1,"black",[0, 0, 80, 20],true,"#cccccc"); var txt1 = new ltextfield(); txt1.x = x; txt1.text = lbl; over.addchild(txt1); var btn = new lbutton(up,over); return btn; }
以上就是用仿actionscript的语法来编写html5——第九篇,仿urlloader读取文件的内容。
其它类似信息

推荐信息