Flex数据交互之HttpService/Json处理
2009-11-15 23:34 LoujaDy 阅读(1785) 评论(0) 收藏 举报第二种采用HttpService与服务器数据交互
其实WebService也可以返回Json数据给Flex,至于.net中使用Json我在这里用到了Newtonsoft.Json 而Flex端用到了as3corelib.swc,网上都可以下,哪下,用法就不在这里说了,没有的,不会用的google一下,很多相关文章.
1.新建一个.net页面和一般处理程序(如果想用两个.net页面,或两个一般处理程序都可以),
我会用.net页面来返回字符串,用一般处理程序来返回Json
选看.net页面下的代码
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace WebServicesDemo
{
public partial class ForFlexData : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//提供两种请求方法数据
Response.Write(ReutrnStringByRequestType(Request.RequestType));
}
//创建数据
private string ReutrnStringByRequestType(string rt)
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Name"));
dt.Columns.Add(new DataColumn("Sex"));
dt.Columns.Add(new DataColumn("Age"));
dt.Columns.Add(new DataColumn("Address"));
string name = string.Empty;
int age = 0;
if (rt.ToLower() == "get") //Get请求方式
{
name = Request.QueryString["name"].ToString();
age = Convert.ToInt32(Request.QueryString["age"]);
}
else if (Request.RequestType.ToLower() == "post")// //Post请求方式
{
name = Request.Form["name"].ToString();
age = Convert.ToInt32(Request.Form["age"]);
}
for (int i = 0; i < 10; i++)
{
dt.Rows.Add(new object[] { name, i % 2 == 0 ? "女" : "男", age, rt });
}//添加十行数据
DataSet ds = new DataSet();
ds.Tables.Add(dt);
return ds.GetXml();
}
}
}
再看看一般处理程序下的代码,它是用来返回Json数据的
using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.IO;
namespace WebServicesDemo
{
/// <summary>
/// Summary description for $codebehindclassname$
/// </summary>
public class ForFlexJsonData : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
JsonSerializer json = new JsonSerializer();
json.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
json.NullValueHandling = NullValueHandling.Ignore;
json.ObjectCreationHandling = ObjectCreationHandling.Replace;
json.MissingMemberHandling = MissingMemberHandling.Ignore;
json.Converters.Add(new DataTableJson());
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.Formatting = Formatting.Indented;
writer.QuoteChar = '"';
json.Serialize(writer,GetData(context.Request));
string output = sw.ToString();
writer.Close();
sw.Close();
context.Response.Write(sw.ToString());
}
//创建数据源
private DataTable GetData(HttpRequest hr)
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Name"));
dt.Columns.Add(new DataColumn("Sex"));
dt.Columns.Add(new DataColumn("Age"));
dt.Columns.Add(new DataColumn("Address"));
for (int i = 0; i < 10; i++)
{
dt.Rows.Add(new object[] { "Dy" + i.ToString(), i % 2 == 0 ? "女" : "男", i * 10, hr.RequestType.ToLower()});
}//添加十行数据
return dt;
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
下面新建一个Flex项目
![]()
Code
<?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/halo" minWidth="1024" minHeight="768">
    <s:layout>
        <s:BasicLayout/>
    </s:layout>
    <fx:Script>
        <![CDATA[
            import com.adobe.serialization.json.JSONDecoder;
            
            import mx.collections.ArrayCollection;
            import mx.controls.Alert;
            import mx.rpc.events.FaultEvent;
            import mx.rpc.events.ResultEvent;
            import mx.rpc.http.HTTPService;
            
            //写义一个HttpService请求s
            private var httpservice:HTTPService;
            
            
            private function InitHttpService():void
            {
                httpservice=new HTTPService();
                httpservice.url="http://192.168.2.8:80/ForFlexData.aspx"                
                httpservice.contentType="application/x-www-form-urlencoded";
                httpservice.useProxy=false;
            
            }
            protected function btnCallGet_clickHandler(event:MouseEvent):void
            {
                if(httpservice==null)
                {
                    InitHttpService();
                }        
                httpservice.addEventListener(FaultEvent.FAULT,OnFault);
                httpservice.addEventListener(ResultEvent.RESULT,OnResult);
                httpservice.method="get";            
                var obj:URLVariables=new URLVariables();
                obj.name="louja";
                obj.age="24";        
                httpservice.request=obj;
                httpservice.send();
                
            }
            protected function btnCallPost_clickHandler(event:MouseEvent):void
            {
                if(httpservice==null)
                {
                    InitHttpService();
                }
                httpservice.addEventListener(FaultEvent.FAULT,OnFault);
                httpservice.addEventListener(ResultEvent.RESULT,OnResult);
                httpservice.method="post";            
                var postData:URLVariables=new URLVariables();
                postData.name="dy";
                postData.age="21";
                httpservice.request=postData;
                httpservice.send();
                
            }
            
            private function OnFault(event:FaultEvent):void
            {
                mx.controls.Alert.show("失败了!","失败");
                
            }
            
            private function OnResult(event:ResultEvent):void
            {
                
                //返回结果
                dgData.dataProvider=event.result.NewDataSet.Table1;
            
                httpservice.removeEventListener(FaultEvent.FAULT,OnFault);
                httpservice.removeEventListener(ResultEvent.RESULT,OnResult);
                httpservice.logout();
                
            }
            
            //发出http请求,返回Json
            protected function btnJson_clickHandler(event:MouseEvent):void
            {
                
                var httpJson:HTTPService=new HTTPService();
                httpJson.url="http://192.168.2.8:80/ForFlexJsonData.ashx"                
                httpJson.contentType="application/x-www-form-urlencoded";
                httpJson.useProxy=false;                    
            
                
                httpJson.addEventListener(FaultEvent.FAULT,OnFault);
                httpJson.addEventListener(ResultEvent.RESULT,OnResultJson);
                httpJson.send();
            }
            
            private function OnResultJson(event:ResultEvent):void
            {
                
                //返回结果
                var data:String=new String(event.result);
                var json:JSONDecoder=new JSONDecoder(data);                
                var arr:Array = (json.getValue().Rows as Array);
                
                var dp:mx.collections.ArrayCollection = new mx.collections.ArrayCollection(arr);
                dgData.dataProvider=dp;    
            }
        ]]>
    </fx:Script>
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
    <s:Panel x="53" y="50" width="426" height="247" id="pnlXml" title="返回的结果">
        <mx:DataGrid x="0" y="0" height="100%" width="100%" id="dgData">
            <mx:columns>
                <mx:DataGridColumn headerText="姓名" dataField="Name"/>
                <mx:DataGridColumn headerText="性别" dataField="Sex"/>
                <mx:DataGridColumn headerText="年龄" dataField="Age"/>
                <mx:DataGridColumn dataField="Address" headerText="请求类型"/>
            </mx:columns>
        </mx:DataGrid>
    </s:Panel>
    <s:Button x="57" y="21" label="Get方式" id="btnCallGet" click="btnCallGet_clickHandler(event)"/>
    <s:Button x="181" y="22" label="Post方式" id="btnCallPost" click="btnCallPost_clickHandler(event)"/>
    <s:Button x="298" y="22" label="httpService返回Json" id="btnJson" click="btnJson_clickHandler(event)"/>
    
</s:Application>
运行Flex项目,呵呵,Get,Post和Json数据都交互成功了!
有表达不清的地方,望大家指出,谢谢!
作者:Louja
出处:http://loujady.cnblogs.com 
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此声明,且在文章页面给出原文连接,否则保留追究法律责任的权利。 
 
                
            
        
浙公网安备 33010602011771号