Flex 3: Getting variables from URL

坚强是说给别人听的谎言 提交于 2019-12-31 01:49:33

问题


If I have an application located at http://sitename.com/myapp/ and i want to pass in a variable via the url (i.e. - http://sitename.com/myapp/?name=Joe), how can I get that name variable into a string var?


回答1:


I use the class Adobe provided 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."); }
      }

    }
  }

UPDATE: An updated version of this class can also be found here, although I haven't tried this one.

UPDATE 2: Here's an example on how to use the Querystring class:

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.");
  }
}



回答2:


Divide 'em with String.split() and conquer:

    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]);
    }

Output:

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


来源:https://stackoverflow.com/questions/6075187/flex-3-getting-variables-from-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!