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

ActionScript3与PHP的通信

在flash应用开发中,经常需要用到和web服务器端的通信,把当前的应用程序状态存储到服务器上或者从服务器端获取信息等等。对于flash来说,他已经提供了对http协议和网络套接字(socket)的支持。对于http协议的支持,flash通过urlrequest、urlloader、urlvariables等类来完成操作。
1、flash中获取外部图片等资源
在actionscript3中,获取外部资源主要通过urlrequest和urlloader两个类完成,可以通过注册urlloader类的complete和progress等事件来监控获取外部资源的状态。
var myloader:urlloader=new urlloader();var myxmllocation:urlrequest = new urlrequest(test.xml);myloader.load(myxmllocation);myloader.contentloaderinfo.addeventlistener(event.complete,xmlloadcomplete);
如果我们获取的外部资源是二进制形式的,我们需要使用loader类来代替urlloader类。
2、flash中的信息传输给web服务器
在flash中需要把数据传递给web服务器,我们只能通过post或者get进行,post动作相对于get可以传递更多的数据,具体区别在于http的entity body,对于post来说,发送的值就在entity body中,对于get来说,entity body永远为空。对于html表单,可以在form的method中指明当前传递数据是post还是get,但是flash中,需要在urlrequest对像中指明当前的操作是post还是get。在flash中,当需要给web服务器传递数据时,需要urlrequest,urlvariables,urlloader等三个类来完成。
var values:urlvariables =new urlvariables(); values.key=”message”; var header:urlrequestheader = new urlrequestheader(pragma, no-cache); var request:urlrequest=new urlrequest(http://localhost/shopguide/data.php); request.data=values; request.requestheaders.push(header); request.method=urlrequestmethod.post; var loader:urlloader=new urlloader(); try { loader.load(request); } catch (error:argumenterror) { trace(an argumenterror has occurred.); } catch (error:securityerror) { trace(a securityerror has occurred.); }
上面的代码,利用urlvariables构造出要传递数据的键值对,这样在php端,就可以通过$_post[“key”]来获取传递的数据。代码中的urlrequestheadere是一个http请求头,即使应用程序具有所请求内容的缓存副本,也应当将请求转发给原始服务器。下面的图是在ie9的开发人员工具下看到的请求信息。
在php服务端,我们只需要echo($_post['key']);就可以获取到请求的信息,第三幅图的响应正文就是php中echo输出的信息。
3、使用php://input获取没有指定键值对的flash请求的内容
在《actionscript 3.0编程》这本书中,他给出的一个传递xml的到web服务器的例子并没有使用urlvariables类来构建键值对,示例代码如下:
var secondsutc:number = new date().time;var dataxml:xml = {secondsutc} ernie guru ;var request:urlrequest = new urlrequest(http://localhost/shopguide/data.php);request.contenttype = text/xml;request.data = dataxml.toxmlstring();request.method = urlrequestmethod.post;var loader:urlloader = new urlloader();try{ loader.load(request);}catch (error:argumenterror){ trace(an argumenterror has occurred.);}catch (error:securityerror){ trace(a securityerror has occurred.);}
这个代码发送的请求与使用urlvariables类的差异在于请求的内容直接是发送的内容,就是没有键值,请求的内容如下:
像这样的请求如何在php中取得数据?后来查资料得知,可以通过php的file_get_contents(php://input)获取。在php中,file_get_contents返回的是一个字符串。通过输出file_get_contents的内容我们可以看到如下响应正文。
关于php://input,请参考这篇文章:
php://input是什么意思?php输入流input的介绍 actionsscript3中还提供了socket类和xmlsocket类,具体使用可以参考《 actionscript 3.0编程》这本书。
其它类似信息

推荐信息