微信小程序使用flex布局

tech2023-12-24  75

微信小程序使用flex布局

If you’re looking to add some pizzazz to your PHP application, look no further – Adobe’s Flex is here to give your interface some polish. In this article Lennart Steinke shows us how to make a Flex widget with a PHP back end. Read carefully, because there’s a quiz at the end: for a limited time, every entrant scores a free Flex reference just for doing the quiz, plus three lucky winners will each receive a free copy of Adobe’s Flex Builder 3!

如果您想在PHP应用程序中增加一些麻烦,那就别无所求– Adob​​e的Flex在这里为您的界面提供一些修饰。 Lennart Steinke在本文中向我们展示了如何使用PHP后端制作Flex小部件。 请仔细阅读,因为最后会有一个测验:在有限的时间内,每位参赛者都将为参加测验而获得免费的Flex参考资料,另外三位幸运获奖者将分别获得一份免费的Adobe Flex Builder 3副本!

Flex is Adobe’s open source web application framework designed for speedy development of web or desktop applications. It allows you to build software that’s then compiled into a Flash (SWF) file, and can be run in any browser with the Flash plugin installed. Best of all, it’s fun to use. You can create great looking applications easily: eye candy and pleasing effects are built in, and can be added to your app with just a few lines of additional code. This allows you to create a cool application in a short amount of time. Oh, and did I mention that it’s fun to use?

Flex是Adobe的开源Web应用程序框架,旨在快速开发Web或桌面应用程序。 它允许您构建软件,然后将其编译成Flash(SWF)文件,并且可以在安装了Flash插件的任何浏览器中运行。 最重要的是,它很有趣。 您可以轻松创建外观精美的应用程序:内置了吸引人的外观和令人愉悦的效果,并且只需几行附加代码即可将其添加到您的应用程序中。 这使您可以在短时间内创建一个很棒的应用程序。 哦,我是否提到使用起来很有趣?

If you’re brand new to Flex, take a look at our earlier Flex tutorial. It’ll walk you through the process of installing the Flex Builder development environment, and introduce you to some of the key concepts of Flex development.

如果您是Flex的新手,请阅读我们之前的Flex教程。 它将引导您完成Flex Builder开发环境的安装过程,并向您介绍Flex开发的一些关键概念。

In this article, we’ll go a step further and learn how to use Flex alongside PHP, by creating a product information widget in Flex that uses PHP to retrieve the product information. Before you start, grab a copy of the Flex Builder 3 demo from Adobe – we’ll be using it to create our widget.

在本文中,我们将更进一步,并通过在Flex中创建一个使用PHP来检索产品信息的产品信息小部件,来学习如何将Flex与PHP一起使用。 在开始之前,请从Adobe 获取Flex Builder 3演示的副本 -我们将使用它来创建我们的小部件。

示例小部件 (The Example Widget)

The small widget we’re going to build shows a product image with a description and a link to a product information page. It will consist of these basic components:

我们将要构建的小窗口小部件显示了带有说明的产品图片以及指向产品信息页面的链接。 它将包含以下基本组件:

a Flex application to display the widget

Flex应用程序以显示小部件 an HTML page that contains the Flash

包含FlashHTML页面 and later, a PHP script to present product data as XML or JSON

之后是一个PHP脚本,用于以XML或JSON形式显示产品数据

To start out, we’ll embed the product information in the Flex application while we build our widget. Once we’ve sorted out the Flex part, we’ll change the code to learn how to retrieve our data from an XML file.

首先,我们将在构建窗口小部件时将产品信息嵌入Flex应用程序中。 整理好Flex部分后,我们将更改代码以了解如何从XML文件检索数据。

Let’s start by creating a new Flex project using Flex Builder. Enter ProductWidget as the project name, make sure that the Application Type is set to Web application, and then hit the Finish button.

让我们开始使用Flex Builder创建一个新的Flex项目。 输入ProductWidget作为项目名称,确保将“应用程序类型”设置为Web应用程序,然后单击“完成”按钮。

This will create a basic project, including a template HTML file to load and display the application, as well as a bare-bones application – ProductWidget.mxml. Unless you changed your Flex Builder layout, the main application file will be visible in the text editor on the right side of the screen. Make sure that the ProductWidget.mxml file is displayed in the editor. If you’re unsure, look for a file named ProductWidget.mxml in the file tree on the left and double-click it. This will ensure that the correct file is loaded.

这将创建一个基本项目,包括用于加载和显示应用程序的模板HTML文件,以及一个准系统应用程序– ProductWidget.mxml。 除非您更改Flex Builder布局,否则主应用程序文件将在屏幕右侧的文本编辑器中可见。 确保在编辑器中显示了ProductWidget.mxml文件。 如果不确定,请在左侧的文件树中查找名为ProductWidget.mxml的文件,然后双击它。 这将确保加载正确的文件。

Inside the file, you’ll see the beginnings of a Flex application, contained in mx:Application tags. We’re going to add a box to contain our widget, a placeholder for an image, and a button which will contain a link. Between the mx:Application tags, add the following code:

在文件内部,您将看到包含在mx:Application标记中的Flex应用程序的开头。 我们将添加一个包含小部件的框,一个图像占位符和一个包含链接的按钮。 在mx:Application标签之间,添加以下代码:

<mx:VBox top="0" left="0" right="0" bottom="0">  <mx:Image id="image" width="150"/>  <mx:LinkButton label="LinkButton" id="link" width="150"/> </mx:VBox>

The mx:VBox is a layout component and it will make sure that the image and the link button are displayed below each other. Both items are also 150 pixels wide.

Hit the Run button in the toolbar (the green button with the white arrow in it) to make sure everything works. Your browser should open and display a rather empty looking page, with the LinkButton we created earlier sitting in the corner.

In the next step, we'll tell our Flex app about our product image, button text, and button link.

Passing Parameters

The most basic way to pass parameters to a Flex application is by adding the parameters to the HTML template which contains our widget. For our example we'll need to supply three values:

the URL to an image to be displayed (imageURL)

要显示的图像的URL( imageURL )

a product description (productTitle)

产品说明( productTitle )

a link to detailed information about the product (productLink)

指向有关产品的详细信息的链接( productLink )

We'll do this by changing the HTML template, which is located in the html-template folder. By default this file contains code to detect the Flash plugin and a link to an installation site in case the client needs to install a Flash plugin. And once we're finished, it'll also contain code to pass parameters to our Flex application.

我们将通过更改HTML模板(位于html-template文件夹中)来完成此操作。 默认情况下,此文件包含用于检测Flash插件的代码,以及在客户端需要安装Flash插件的情况下指向安装站点的链接。 完成后,它还将包含将参数传递给Flex应用程序的代码。

There are two calls to a function, AC_FL_RunContent, in the file. Make sure you use the one that's used to call your SWF file (the other one is to update the Flash Player if an outdated version was detected). It was around line 77 in my template. This call contains all the parameters passed to the Flex application. In order to pass data to your Flex application, you need to add an additional parameter named flashVars; this parameter can contain several other parameters encoded with HTML URL encoding, like the variables in a GET call. I'm using a free image from stock.xchng by nitewind23, and the image's detail screen will serve as a product for this demonstration:

文件中有两个对函数AC_FL_RunContent调用。 确保使用一个用于调用SWF文件的文件(另一个是如果检测到过时的版本,则更新Flash Player)。 它在我模板的第77行附近。 该调用包含传递给Flex应用程序的所有参数。 为了将数据传递到Flex应用程序,您需要添加一个名为flashVars的附加参数; 此参数可以包含其他一些用HTML URL编码编码的参数,例如GET调用中的变量。 我正在使用nitewind23的stock.xchng中的免费图像 ,该图像的详细信息屏幕将用作此演示的产品:

} else if (hasRequestedVersion) {  // if we've detected an acceptable version    // embed the Flash Content SWF when all tests are passed    AC_FL_RunContent(      "src", "${swf}",      "width", "${width}",      "height", "${height}",      "align", "middle",      "id", "${application}",      "quality", "high",      "bgcolor", "${bgcolor}",      "name", "${application}",      "allowScriptAccess","sameDomain",      "type", "application/x-shockwave-flash",      "pluginspage", "http://www.adobe.com/go/getflashplayer",      "flashVars", "imageURL=http://www.sxc.hu/pic/m/n/ni/nitewind23/638995_dead_rubber_ducky.jpg&productTitle=Rubber%20duck&productLink=http://www.sxc.hu/photo/638995"    );    // ...   }

This is enough to make it work if the user has JavaScript enabled in the browser. For users browsing without JavaScript, you'll also need to add the parameters in the noscript block of the template.

如果用户在浏览器中启用了JavaScript,这足以使其正常工作。 对于不使用JavaScript浏览的用户,您还需要在模板的noscript块中添加参数。

Our application will receive parameters from the HTML template - now we need to tell the application how to use them.

我们的应用程序将从HTML模板接收参数-现在我们需要告诉应用程序如何使用它们。

Code in .mxml files has to be placed in a mx:Script block. We'll add the block after the closing bracket of the mx:VBox:

.mxml文件中的代码必须放在mx:Script块中。 我们将在mx:VBox括号后添加该块:

<mx:Script>  <![CDATA[      private var linkURL: String ="";      private function onCreationComplete() : void      {        setData(          application.parameters.imageURL,          application.parameters.productTitle,          application.parameters.productLink        );      }      private function setData(imageURL: String, productTitle:String, productLink:String) : void      {        image.source = imageURL;        link.label = productTitle;        linkURL = productLink;      }      private function onLinkClicked():void      {        navigateToURL(new URLRequest(linkURL));      }    ]]>   </mx:Script>

The onCreationComplete method reads the parameters that were passed from the HTML file and calls another function, setData, which will populate variables for our code with the parameters we received from the HTML template. Since this method is called as soon as the application is created, we can be sure that our data will be set right at the beginning.

onCreationComplete方法读取从HTML文件传递的参数,并调用另一个函数setData ,该函数将使用从HTML模板接收的参数填充代码变量。 由于此方法是在创建应用程序后立即调用的,因此我们可以确保在开始时就设置好我们的数据。

The setData function takes three parameters: imageURL, productTitle, and productLink. We'll use the imageURL to set the source of the image, and the productTitle can be used to set the label displayed on the link button. The productLink needs to be saved in the linkURL variable we just defined, so we can use it as soon as the user clicks the link.

setData函数采用三个参数: imageURL , productTitle和productLink 。 我们将使用imageURL设置图像的来源,而productTitle可以用于设置显示在链接按钮上的标签。 productLink需要保存在我们刚刚定义的linkURL变量中,因此我们可以在用户单击链接后立即使用它。

Finally, the onLinkClicked function will navigate to the link defined in the variable linkURL. We'll attach that function to the button in the next step.

最后, onLinkClicked函数将导航到变量linkURL定义的链接。 下一步,我们将该功能附加到按钮上。

Let's go back to the mx:VBox tag we created earlier, and look for the link button. We'll add a click handler like so:

让我们回到前面创建的mx:VBox标记,然后查找链接按钮。 我们将添加一个点击处理程序,如下所示:

<mx:LinkButton label="LinkButton" id="link" click="onLinkClicked()"/>

And finally, we need to make all of this happen as soon as the application is loaded. We'll add a handler to the application, creationComplete, to run our onCreationComplete function just as soon as - you guessed it - the creation of the element is complete. Look for the mx:Application tag at the top, and add the handler:

最后,我们需要在加载应用程序后立即执行所有这些操作。 我们将在应用程序中添加一个处理程序creationComplete ,以在您猜onCreationComplete立即运行我们的onCreationComplete函数。 在顶部查找mx:Application标签,然后添加处理程序:

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"  layout="absolute"    creationComplete="onCreationComplete()" >

Your complete .mxml file should look like the code in Listing 1.

完整的.mxml文件应类似于清单1中的代码。

All done. Hit the Run button and give it a try! The result should look a little like the following:

全做完了。 点击运行按钮,尝试一下! 结果应类似于以下内容:

增强它 (Spicing It Up)

Because it's so easy, let's add a small piece of eye candy to the application and fade in the image. This is as simple as adding completeEffect="Fade" to the mx:Image tag:

因为它是如此简单,所以我们在应用程序中添加一小撮眼球糖果并淡入图像。 这就像向mx:Image标签添加completeEffect="Fade"一样简单:

<mx:Image id="image" height="150" completeEffect="Fade"/>

Now, run the application again - you should see that the duck image will fade in gently. There are a lot of predefined effects in Flex, and it's very easy to customize them or to create your own. For more information take a look at Working with effects in the Adobe LiveDocs.

现在,再次运行该应用程序-您应该看到鸭子图像会逐渐淡入。 Flex中有很多预定义的效果,可以很容易地自定义它们或创建自己的效果。 有关更多信息,请参阅使用Adobe LiveDocs中的效果 。

So, now we have the basic framework to provide the Flex application with data. Next, it's time to provide that data in some more exciting ways: let's use PHP to create some XML for our application to consume.

因此,现在我们有了为Flex应用程序提供数据的基本框架。 接下来,是时候以一些更令人兴奋的方式提供数据了:让我们使用PHP为应用程序创建一些XML以供使用。

处理XML数据 (Working with XML Data)

If your app can produce XML data, the next part of this tutorial will show you how to process that data in Flex. XML can be easily created, is readable by humans, and the Flex support for XML is neat. These are all good reasons to use it, so let's have a look at the work involved to do so.Before we start: It's important to remember that Flash is extremely strict about accessing data from a different domain to the one where the SWF is kept. You'll either need to run your Flex app from the same domain as your PHP scripts, or create a cross-domain policy file on the server where your PHP lives. For more information about cross-domain policy files and the Flash security model, check out this Adobe Developer Connection article.

如果您的应用程序可以生成XML数据,那么本教程的下一部分将向您展示如何在Flex中处理该数据。 XML易于创建,易于人们阅读,并且对XML的Flex支持十分简洁。 这些都是使用它的充分理由,所以让我们看一下使用它的工作。 在开始之前:请务必记住Flash对于从另一个域访问保留SWF的数据非常严格。 您要么需要从与PHP脚本相同的域中运行Flex应用程序,要么需要在PHP所在的服务器上创建跨域策略文件。 有关跨域策略文件和Flash安全模型的更多信息,请参见这篇Adobe开发人员连接文章。

Since we're going to use HTTP to retrieve the data, we'll use a Flex class called HTTPService, which will handle all the heavy lifting for us. We'll tell the HTTPService where to connect to and what to do with the returned data.

由于我们将使用HTTP来检索数据,因此我们将使用一个名为HTTPService的Flex类,它将为我们处理所有繁重的工作。 我们将告诉HTTPService在何处连接以及如何处理返回的数据。

To try it out, we'll need to code up a simple PHP data provider. In a real-world situation, you'd be pulling the information from a database, but for this example we'll keep it simple and hard-code these values. Here's a PHP script that uses a function to fetch the data, creates a variable to hold that data, and then outputs the data in XML format:

要进行尝试,我们需要编写一个简单PHP数据提供程序。 在现实世界中,您可能会从数据库中提取信息,但是对于本示例,我们将使其保持简单并对这些值进行硬编码。 这是一个PHP脚本,该脚本使用一个函数来获取数据,创建一个变量来保存该数据,然后以XML格式输出数据:

<?php  header("Content-type: text/xml");    function getData() {      $data["productLabel"] = "Rubber duck";      $data["productLink"] = "http://www.sxc.hu/photo/638995";      $data["imageURL"] = "http://www.sxc.hu/pic/m/n/ni/nitewind23/638995_dead_rubber_ducky.jpg";      return $data;      }    $product = getData();   ?>   <?php echo '<?xml version="1.0"?>'; ?>   <data>    <product>       <label><?php echo $product["productLabel"] ?></label>       <link><?php echo $product["productLink"] ?></link>       <imageURL><?php echo $product["imageURL"] ?></imageURL>    </product>   </data>

In our Flex app, we'll define an HTTPService pointing to our PHP page by adding an HTTPService block to our code. Inside this block we need to define a unique name for our service (id) so that we can refer to it in our ActionScript code, the URL to call (url), and the result format (resultFormat).

在我们的Flex应用程序,我们将定义一个HTTPService通过添加指向我们PHP页面HTTPService块到我们的代码。 在此块内,我们需要为服务定义一个唯一的名称( id ),以便我们可以在ActionScript代码,调用的URL( url )和结果格式( resultFormat )中引用它。

One point to keep in mind is that the call will be asynchronous: the send method will return immediately and the service will be called in the background. So, how do we access the data? The HTTPService provides two callback methods for this purpose: one for when the result is successful (result), and one for when it fails (fault).

要记住的一点是,该调用将是异步的:send方法将立即返回,并且该服务将在后台调用。 那么,我们如何访问数据? HTTPService为此提供了两种回调方法:一种用于结果成功时( result ),一种用于失败时( fault )。

Here's the code we'll use to define our HTTPService block, which we'll place before the mx:Script block:

这是用于定义HTTPService块的代码,该代码将放置在mx:Script块之前:

<mx:HTTPService  id="productService"    url="http://www.example.com/service.php"      resultFormat="e4x"    result="serviceLoaded(event)"    fault="serviceError(event)"   />

When an HTTPService will retrieve XML, you should set the expected format, resultFormat, to e4x - ECMAScript for XML. Using this result type allows us to employ a lot of convenient JavaScript functions when working with the returned XML.

当HTTPService检索XML时,应将期望的格式resultFormat设置为e4x -ECMAScript for XML。 使用此结果类型使我们在处理返回的XML时可以使用许多便捷JavaScript函数。

If you're wondering why it's called ECMAScript instead of JavaScript, well, the Ecma International group defines the JavaScript language standards. The idea is that different implementations of JavaScript (for example, different browsers) ought to define at least the functionality defined by the Ecma International group. This core scripting language is also called ECMAScript.

如果您想知道为什么将它称为ECMAScript而不是JavaScript,那么Ecma International小组将定义JavaScript语言标准。 这个想法是,JavaScript的不同实现(例如,不同的浏览器)应该至少定义由Ecma International组定义的功能。 这种核心脚本语言也称为ECMAScript。

Next, we need to define what we'll do with the data we receive from the HTTPService. We know the result format, so we simply treat the event result as XML. This allows us to access the data in the XML like a normal object. The top level element (data in our example) will be mapped to be the actual XML object (xmlData in our example), so we can access the product level by using xmlData.product. Since the XML could contain several product elements, we need to specify which one we want - in this example, it will always be the first one (xmlData.product[0]). The elements below the product can then be accessed via their element directly. Just passing the data to our existing setData function will do the trick for us. We'll do all this in a function, serviceLoaded:

接下来,我们需要定义如何处理从HTTPService接收的数据。 我们知道结果格式,因此我们仅将事件结果视为XML。 这使我们可以像普通对象一样访问XML中的数据。 顶级元素(本例中的data )将被映射为实际的XML对象(本例中的xmlData ),因此我们可以使用xmlData.product来访问产品级别。 由于XML可能包含多个产品元素,因此我们需要指定我们想要的产品元素-在此示例中,它将始终是第一个( xmlData.product[0] )。 然后可以直接通过其元素访问产品下方的元素。 只需将数据传递到我们现有的setData函数即可为我们解决问题。 我们将在serviceLoaded函数中完成所有这些操作:

private function serviceLoaded(event: ResultEvent) : void {    var xmlData: XML = event.result as XML;    setData(      xmlData.product[0].imageURL,        xmlData.product[0].label,        xmlData.product[0].link        );   }

We also need to define another function, serviceError, for when there is a problem with the HTTPService. Normally, you would want to retry or specify some other, more meaningful action, but for now we'll simply add a trace:

我们还需要定义另一个函数, serviceError ,因为当有与问题HTTPService 。 通常,您可能想重试或指定其他更有意义的操作,但是现在我们仅添加跟踪:

private function serviceError(event: FaultEvent) : void {    trace("Unable to get XML:" + event.fault.message);   }  

Listing 2 shows the complete source for the XML version, with our HTTPService and the related functions.

清单2显示了XML版本的完整资源,以及我们的HTTPService和相关功能。

Next, we'll investigate how to consume data provided in the JSON format.

接下来,我们将研究如何使用JSON格式提供的数据。

使用JSON (Using JSON)

We'll now change our example to work with data provided in JSON - the JavaScript Object Notation format. If you're new to the idea, there's a good explanation of the JSON from the JSON web site:

现在,我们将更改示例以使用以JSON(JavaScript对象表示法格式)提供的数据。 如果您是这个想法的新手,那么可以从JSON网站很好地解释JSON:

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

JSON(JavaScript对象表示法)是一种轻量级的数据交换格式。 人类易于阅读和书写。 机器很容易解析和生成。 它基于JavaScript编程语言(标准ECMA-262第三版-1999年12月)的子集。JSON是一种文本格式,它完全独立于语言,但是使用C语言家族(包括C语言)的程序员熟悉的约定。 ,C ++,C#,Java,JavaScript,Perl,Python等。 这些属性使JSON成为理想的数据交换语言。

To use JSON in Flex, we'll need to incorporate a library called ActionScript 3 Corelib, which contains JSON support, MD5 hashing, and some other useful functionality that's currently missing from Flex. You can download the library from its Google Code project page. Unzip the file, and note where you placed it. We need to tell Flex Builder where to find it in the next step.

要在Flex中使用JSON,我们需要合并一个名为ActionScript 3 Corelib的库,该库包含JSON支持,MD5哈希以及Flex当前缺少的一些其他有用功能。 您可以从其Google Code项目页面下载该库。 解压缩文件,并记下放置位置。 我们需要告诉Flex Builder下一步在哪里找到它。

Back in Flex Builder, right-click your ProductWidget project, and choose Properties from the context menu. Now click on the Flex Build Path item, and choose the Library Path tab. You should be in a window that looks like this:

返回Flex Builder,右键单击您的ProductWidget项目,然后从上下文菜单中选择“属性”。 现在,单击“ Flex构建路径”项,然后选择“库路径”选项卡。 您应该在一个看起来像这样的窗口中:

Click on Add SWC and navigate to the place where you unzipped the file. The SWC file needed can be found in the library's lib/ subfolder, and it should be called as3corelib.swc. After selecting that file, click OK, and Flex Builder will now happily work with JSON encoded data.

单击“添加SWC”,然后导航到您解压缩文件的位置。 所需的SWC文件可在库的lib /子文件夹中找到,并且应称为as3corelib.swc。 选择该文件后,单击“确定”,Flex Builder现在将愉快地使用JSON编码的数据。

Let's now examine the code we'll use to create JSON-formatted data in PHP. PHP5 has integrated JSON support, but for older versions you'll need an additional PHP library - I'd suggest you download and use the Services_JSON library from PEAR.

现在,让我们检查用于在PHP中创建JSON格式的数据的代码。 PHP5集成了JSON支持,但是对于较旧的版本,您将需要一个额外PHP库-我建议您从PEAR下载并使用Services_JSON库。

The PHP code for outputting JSON text is quite similar to the XML example. This time, we'll define a class to hold the data first, then our getData function will create a new instance of this class and fill it with dummy data. Finally, we'll output the JSON-encoded object:

用于输出JSON文本PHP代码与XML示例非常相似。 这次,我们将定义一个类来首先保存数据,然后我们的getData函数将创建该类的新实例,并用伪数据填充它。 最后,我们将输出JSON编码的对象:

<?php      class Data      {        public $imageURL;        public $productTitle;        public $productLink;      }      function getData()      {        $data = new Data();        $data->imageURL = "http://www.sxc.hu/pic/m/n/ni/nitewind23/638995_dead_rubber_ducky.jpg";        $data->productTitle = "Rubber duck";        $data->productLink = "http://www.sxc.hu/photo/638995";        return $data;      }      echo json_encode(getData());     ?>    

Fairly straightforward!

非常坦率的!

On the Flex side, we need to complete a few important steps: first, we must include the JSON class from the library we added; next, we'll change the HTTPService block to point to the new service; finally, we'll alter the serviceLoaded method to decode the JSON text.

在Flex方面,我们需要完成一些重要步骤:首先,我们必须包括添加的库中的JSON类; 接下来,我们将更改HTTPService块以指向新服务; 最后,我们将更改serviceLoaded方法以解码JSON文本。

First, at the top of our mx:Script block, we'll instruct Flex to use the JSON class from the ActionScript 3 Corelib library:

首先,在我们的mx:Script块的顶部,我们将指示Flex使用ActionScript 3 Corelib库中的JSON类:

import com.adobe.serialization.json.JSON;

We'll also tell the HTTPService about the location of the JSON service. JSON results are returned as text, so we'll also need to change the resultFormat to text:

我们还将告诉HTTPService JSON服务的位置。 JSON结果以文本形式返回,因此我们还需要将resultFormat更改为text :

<mx:HTTPService  id="productService"      url="http://www.example.com/service.php"      resultFormat="text"      result="serviceLoaded(event)"      fault="serviceError(event)"     />

Finally, we need to alter the serviceLoaded method so that it can decode the JSON text and turn it into a Flex object. Here's a new version of serviceLoaded:

最后,我们需要更改serviceLoaded方法,以便它可以解码JSON文本并将其转换为Flex对象。 这是serviceLoaded的新版本:

private function serviceLoaded(event: ResultEvent) : void {      var rawData:String = String(event.result);      var data:Object = JSON.decode(rawData);      setData(          data.imageURL,          data.productTitle,          data.productLink        );     }

The complete source of our final example can be seen in Listing 3.

清单3中显示了我们最后一个示例的完整资源。

在HTTPRequests中使用参数 (Using Parameters in HTTPRequests)

So far, all of our examples requested data directly. In real-world examples, chances are that you'll need to pass parameters to the services in question, such as a search term or a tag. To set parameters in the HTTPService you add a mx:Request tag containing the parameters to pass, and a method to use for the request. If we want to pass a parameter named search it would look like this:

到目前为止,我们所有的示例都直接请求数据。 在实际示例中,您很可能需要将参数传递给所涉及的services ,例如搜索词或标签。 要在HTTPService设置参数,您需要添加一个mx:Request标记,其中包含要传递的参数以及用于请求的方法。 如果我们想传递一个名为search的参数,它将看起来像这样:

<mx:HTTPService  id="personRequest"      url="http://www.example.com/service_json.php"      resultFormat="text"      result="serviceLoaded(event)"      fault="serviceError(event)"      method="GET"      >      <mx:Request>        <search>duck</search>      </mx:Request>     </mx:HTTPService>
开始Pimpin' (Start Pimpin')

As you can see, connecting Flex with PHP is quite easy. If your PHP app exposes a service returning XML or JSON data, Flex can grab this data in almost no time. Happy coding!

如您所见,将Flex与PHP连接非常容易。 如果您PHP应用程序公开了返回XML或JSON数据的服务,则Flex几乎可以立即获取该数据。 祝您编码愉快!

测验 (Quiz)

Feeling confident? Test your knowledge of this article and take our quiz. Just for answering the quiz, you'll be able to download Tour de Flex, a unique desktop application that lets you explore resources such as core Flex components, Adobe AIR documentation and data integration, and third-party plugins.

感觉有信心? 测试您对本文的了解并参加我们的测验 。 仅为了回答测验,您将能够下载Tour de Flex,这是一个独特的桌面应用程序,可让您浏览诸如Flex核心组件,Adobe AIR文档和数据集成以及第三方插件之类的资源。

What's more, everyone who submits their details by the 6th of May 2009 will go in the draw to win a copy of Adobe Flex Builder 3. There are three copies to give away, so give it a try!

此外,所有在2009年5月6日之前提交详细信息的人都将参加抽奖,以赢得Adobe Flex Builder 3的副本。这里有三本可以赠送,请尝试一下!

翻译自: https://www.sitepoint.com/pimp-php-app-flex/

微信小程序使用flex布局

最新回复(0)