Flex 3:从URL获取变量

时间:2011-05-20 16:52:01

标签: flex get urlvariables

如果我的应用程序位于http://sitename.com/myapp/并且我想通过url传递一个变量(即 - http://sitename.com/myapp/?name=Joe),我怎样才能将该名称变量转换为字符串var?

2 个答案:

答案 0 :(得分:3)

我使用Adobe提供的in this article类。

  package 
  {
    import flash.external.*;
    import flash.utils.*;

    public class QueryString 
    {

      private var _queryString:String;
      private var _all:String;
      private var _params:Object;

      public function get queryString():String
      {
        return _queryString;
      }
      public function get url():String
      {
        return _all;
      }
      public function get parameters():Object
      {
        return _params;
      }           


      public function QueryString()
      {

        readQueryString();
      }

      private function readQueryString():void
      {
        _params = {};
        try 
        {
          _all = 
  ExternalInterface.call("window.location.href.toString");
          _queryString =
  ExternalInterface.call("window.location.search.substring", 1);
          if(_queryString)
          {

            var params:Array = _queryString.split('&');
            var length:uint = params.length;

            for (var i:uint=0,index:int=-1; i 0)
              {
                var key:String = kvPair.substring(0,index);
                var value:String = kvPair.substring(index+1);
                _params[key] = value;
              }
            }
          }
        }catch(e:Error) { trace("Some error occured.
  ExternalInterface doesn't work in Standalone player."); }
      }

    }
  }

更新:此类的更新版本也可以be found here,但我还没有尝试过这个版本。

更新2: 这是一个关于如何使用Querystring类的示例:

public function CheckForIDInQuerystring():void
{
  // sample URL: http://www.mysite.com/index.aspx?id=12345
  var qs:QueryString = new QueryString;

  if (qs.parameters.id != null)
  {   
    // URL contains the "id" parameter
    trace(qs.parameters.id);
  }
  else
  {                 
    // URL doesn't contain the "id" parameter
    trace("No id found.");
  }
}

答案 1 :(得分:1)

用String.split()划分它们并征服:

    var url:String = "http://www.xxx.zzz/myapp?arg1=vae&arg2=victus";
    var params:String = url.substr(url.lastIndexOf("?") + 1);
    if (params.length == url.length) return; //no params
    for each (var pair:String in params.split("&"))
    {
        trace("Got parameter:");
        var nameValue:Array = pair.split("=");
        trace("name: " + nameValue[0] + ", value: " + nameValue[1]);
    }

输出:

Got parameter:
name: arg1, value: vae
Got parameter:
name: arg2, value: victus