Saturday, June 1, 2013

AS 3: Opening a url with utf-8 encode parameters

Not sure if any of you out there might encounter the following problem, but with all these social networking sites floating around the Internet, there might be a requirement that requires you to open up a website with some parameters. Therefore...

Here's the source code of my main application - SimpleTwitterPost.mxml
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
      xmlns:s="library://ns.adobe.com/flex/spark" 
      xmlns:mx="library://ns.adobe.com/flex/mx"
      backgroundColor="#CDCDCD">
 
 <fx:Script>
  <![CDATA[
   //A default message.
   private var msg:String = "僕は男性です。";
   //URL of Twitter.
   private var strTwitter:String = "http://www.twitter.com";
   
   //Label
   private var strLabel:String = "Please enter your " +
    "message in the text box provided below."
   
   //Upon clicking on one of the buttons,
   protected function clickHandler(event:MouseEvent):void
   {
    var tempStr:String = txtInput.text;
    if(event.currentTarget == btn1)
    {
     //encode the message in utf-16,
     //which is not supported across most browsers.
     tempStr = escape(tempStr);
    }else{
     //encode the message in utf-8,
     //which is supported across all browsers.
     tempStr = encodeURIComponent(tempStr);
    }
    tempStr = strTwitter + "?status=" + tempStr;
    
    var tempURLReq:URLRequest;
    tempURLReq = new URLRequest(tempStr);
    
    //Open the URL in a new window.
    navigateToURL(tempURLReq, "_blank");
   }
  ]]>
 </fx:Script>
 <fx:Declarations>
  <!-- Place non-visual elements (e.g., services, value objects) here -->
 </fx:Declarations>
 <s:VGroup verticalAlign="middle" 
     horizontalAlign="center" 
     width="100%" 
     height="100%">
  <s:Spacer height="100%"/>
  <s:Label text="{strLabel}"/>
  <s:TextArea maxChars="140"  
     id="txtInput"
     heightInLines="4"
      width="50%" 
     text="{msg}"/>
  <s:Button label="Using escape()" 
      click="clickHandler(event)" 
      width="200"
      id="btn1"/>
  <s:Button label="Using encodeURIComponent()"
      click="clickHandler(event)"
      width="200"
      id="btn2"/>
  <s:Spacer height="100%"/>
 </s:VGroup>
</s:Application>
* Click here for the demo shown in this post.
^ Click here for the source files for the demo.

No comments:

Post a Comment