【问题标题】:Adobe Air, and getting data through JSONPAdobe Air,并通过 JSONP 获取数据
【发布时间】:2013-08-19 22:43:05
【问题描述】:

我将 javascript/jQuery 与 Adob​​e Air 结合使用,但由于某种原因,我无法使其正常工作,以便从服务器中提取数据。

这在浏览器中运行良好(各个项目正确附加到 ul,并且弹出窗口显示“SUCCESS”),但是当我在 Adob​​e Air 中运行它时,它似乎无法正常工作(得到一个显示“ ERROR”,并且 ul 没有被写入)。

这是我的 JS 代码:

jQuery("#whatever").append("<ul><li>test</li></ul>");
var url = 'http://www.mysite.com/test.php?callback=?';
var data = '';

jQuery.ajax({
   type: 'GET',
    url: url,
    async: false,
    jsonpCallback: 'jsonCallback',
    contentType: "application/json",
    dataType: 'jsonp',
    success: function(data) {
        alert("SUCCESS");
       jQuery.each(data, function() {
          jQuery.each(this, function(k, v) {
            jQuery("<li></li>").html(v.siteName).appendTo("#whatever ul");
          });
        });
    },
    error: function(e) {
        alert("ERROR");
       console.log(e.message);
    }
});

以及服务器上的 JSON 代码:

jsonCallback(
{
    "sites":
    [
        {
            "siteName": "JQUERY4U",
            "domainName": "http://www.jquery4u.com",
            "description": "#1 jQuery Blog for your Daily News, Plugins, Tuts/Tips &amp; Code Snippets."
        },
        {
            "siteName": "BLOGOOLA",
            "domainName": "http://www.blogoola.com",
            "description": "Expose your blog to millions and increase your audience."
        },
        {
            "siteName": "PHPSCRIPTS4U",
            "domainName": "http://www.phpscripts4u.com",
            "description": "The Blog of Enthusiastic PHP Scripters"
        }
    ]
}
);

【问题讨论】:

  • 我认为您不能在 Adob​​e AIR 中使用 JavaScript/jQuery。它必须是您正在开发的基于 Adob​​e AIR 的应用程序。请发布您的 AIR 应用程序的 Flex/Flash Builder 代码。
  • 您可以在基于 AIR 的应用程序中从服务器获取数据,而无需使用 javascript 或 jQuery。我将发布我的示例代码,以便为您在 actionscript 3.0 中从服务器获取数据。

标签: jquery ajax air adobe


【解决方案1】:

这是在基于 Adob​​e AIR 的应用程序中从服务器获取数据的方法。

<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
                       xmlns:s="library://ns.adobe.com/flex/spark"
                       xmlns:mx="library://ns.adobe.com/flex/mx"
                       applicationComplete="init()" 
                       width="620" height="740" 
                       frameRate="30">
<fx:Script>
    <![CDATA[

        import com.adobe.serialization.json.JSON;

        // var ini
        // ------------------------------------------------------------------------
        private var filePath:String = "http://www.mysite.com/test.php?callback=?";// URL or path to JSON Source // can be "assest/jsondata.txt";
        private var urlLoader:URLLoader;
        private var jsonDataArray:Array;
        private var jsonObj:Object;
        private var request:URLRequest;
        private var variables:URLVariables;
        private var requestFilters:String;
        private var requestHeaders:Array;//used for content-type headers and such
        private var arr:Array = new Array();// saving all objects to dataGrid
        // ------------------------------------------------------------------------


        // ------------------------------------------------------------------------
        private function init():void
        {
            requestHeaders = new Array(new URLRequestHeader("content-type","application/json"));//add as many comma separated headers as you need to send to server
            // Add event listener for button click
            btn.addEventListener(MouseEvent.CLICK,loadJSONData);
        }
        // ------------------------------------------------------------------------




        // ------------------------------------------------------------------------
        private function loadJSONData(e:MouseEvent=null):void
        {
            // Load file
            urlLoader = new URLLoader();
            urlLoader.addEventListener(Event.COMPLETE, fileLoaded,false,0,true);
            urlLoader.addEventListener(IOErrorEvent.IO_ERROR, fileLoadFailed);
            request = new URLRequest();
            request.method = URLRequestMethod.POST;//use URLRequestMethod.GET if you want
            request.requestHeaders = requestHeaders;//headers to send
            request.data = 'jsonCallback';//can send data/parameters with this request to server. If server requires data/parameters sent as JSON string, you can accomplish it passing JSON String like this: request.data = '{"jsonrpc": "2.0", "method": "SportsAPING/v1.0/listEventTypes", "params": { "filter" : {} }, "id": 1}';
            request.url = filePath;
            urlLoader.load(request);
        }
        // ------------------------------------------------------------------------


        private function fileLoadFailed(e:Event):void
        {
            trace("Failed: "+e.target.data.toString());
        }



        // ------------------------------------------------------------------------
        private function fileLoaded(e:Event):void
        {
            // Clean up file load event listeners
            urlLoader.removeEventListener(Event.COMPLETE, fileLoaded);

            // If you wanted to get the data from the event use the line below
            //var urlLoader:URLLoader = URLLoader(event.target);

            trace("urlLoader.data: "+urlLoader.data+", Data type: "+typeof(urlLoader.data));

            var Obj:Object = urlLoader.data;

            // Parse the response to get Array or Object depending on how the JSON is formatted on Server.
            //jsonDataArray = com.adobe.serialization.json.JSON.decode(urlLoader.data);

            // converts urlLoader.data to a localized Object or Array

            // check if the returned data is an Object
            if(typeof(com.adobe.serialization.json.JSON.decode(urlLoader.data))=='object')
            jsonObj = com.adobe.serialization.json.JSON.decode(urlLoader.data);
            // if data returned is an Array
            else if(typeof(com.adobe.serialization.json.JSON.decode(urlLoader.data))=='object' && com.adobe.serialization.json.JSON.decode(urlLoader.data).length>2)
            jsonDataArray = com.adobe.serialization.json.JSON.decode(urlLoader.data);
            /* Your Data Format
            {
                    "sites":
                    [
                        {
                            "siteName": "JQUERY4U",
                            "domainName": "http://www.jquery4u.com",
                            "description": "#1 jQuery Blog for your Daily News, Plugins, Tuts/Tips &amp; Code Snippets."
                        },
                        {
                            "siteName": "BLOGOOLA",
                            "domainName": "http://www.blogoola.com",
                            "description": "Expose your blog to millions and increase your audience."
                        },
                        {
                            "siteName": "PHPSCRIPTS4U",
                            "domainName": "http://www.phpscripts4u.com",
                            "description": "The Blog of Enthusiastic PHP Scripters"
                        }
                    ]
                }
            */



            // now you should be able to access the data like this:
            trace(jsonObj.sites[0].domainName);
            // or
            trace(jsonDataArray[0].siteName);
            // Now you can loop through your received data as usual.
        }
        // ------------------------------------------------------------------------




    ]]>
</fx:Script>

<mx:DataGrid id="dg" top="100" width="600" height="600" horizontalCenter="0">
    <mx:columns>
        <mx:DataGridColumn width="200" dataField="name" headerText="Name"/>
        <mx:DataGridColumn dataField="value" headerText="Value"/>
    </mx:columns>
</mx:DataGrid>
<mx:Label top="15" color="#0D595A" fontSize="30" fontWeight="bold" horizontalCenter="4"
          text="Get JSON Data From Server"/>
<mx:Button id="btn" top="70" width="200" label="Get JSON Data from Server"
           chromeColor="#A7FEFF" fontWeight="bold" horizontalCenter="0"/>
</s:WindowedApplication>

现在,这是帮助您开始使用从服务器加载 JSON 数据的 Adob​​e AIR 应用程序的完整代码。

我在这个例子中使用import com.adobe.serialization.json.JSON;。并且需要包含它以将接收到的字符串格式的 JSON 数据解析/解码为本地 ActionScript 对象。

您可以从 GITHUB 下载as3corelib。

如果您使用 Adob​​e Flash 创建您的 AIR 应用程序,那么您必须在您的库/源路径中包含此库。

如果您和我一样使用的是 Adob​​e Flash Builder 4.6 Premium,那么:

1) 在 Adob​​e Flash Builder 中,确保您处于 Flash Builder 透视图中,从包资源管理器中,右键单击您的项目并选择属性。 (这将打开您的项目属性)

2)在项目的属性对话框中,选择“Flex Build Path”。

3) 在“Flex Build Path”对话框中,选择选项卡:“Library path”。

4) 点击右侧的“添加SWC”按钮。并浏览到:“as3corelib.swc”文件的位置。 (最好将此文件放在应用程序主目录中的“libs”文件夹/目录中,其中“bin-debug”目录也驻留。)现在选择文件并单击“确定”按钮。

5) 再次单击“确定”按钮关闭项目的属性对话框。

6) 现在保存所有项目文件和所有内容,然后关闭 Flash Builder。

7) 现在重新启动 Flash Builder。运行或调试您的项目。您应该能够在控制台日志中看到我们的trace 语句的输出。

8) 如果在编译您的项目时出现错误,那么您还必须在项目的“src中包含com.adobe.serialization.json.JSON; 包" 目录,通过解压缩包含 as3corelib 的源 ActionScript 类的 Zip 文件。

9) 现在应该可以了。最好再次重新启动 Flash Builder。现在您的项目的 SRC 目录应该有一个 com 目录,其中包括 的其他目录和 ActionScript 类as3corelib 包。 (至少我现在已经添加了as3corelib.swc和包的源文件没有问题)

在 github 上下载“as3corelib”。它包含 lib 目录中的 as3corelib.swc 文件和 srccom.adobe.serialization.json 包的 ActionScript 3.0 源类/strong> 目录。 (您可能需要将 com 目录及其所有内容复制到项目 root 中的 libs 目录 目录。这样你就可以在你的代码中调用它的 decode 和 encode 方法,并编译到你的 SWF 和 AIR 文件。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    • 2010-12-02
    • 2011-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多