xml地图|网站地图|网站标签 [设为首页] [加入收藏]

ajax学习笔记,面向对象

由于组里项目大多的javascript,css等客户端工作是另一同事在负责,该同事又特忙无法重构,老大也就只是提建议并未立即实施重构。但是我前些日子也改过些许客户端的小bug,确实那代码看得让人有些云里雾里,不知身在哪山,轻易不敢动代码,于是就自己动手鼓捣起我曾又爱又恨的javascript来,自己写一个简单的js实现namespace,继承,重载等面向对象的特性.欢迎拍砖灌水
.定义namespace
Namesapce.js

            var prm = Sys.WebForms.PageRequestManager.getInstance();
            alert(prm.get_isInAsyncPostBack()); //判断是否为异步提交
一.Ajax类

 

复制代码 代码如下:

betway 1
betway,<form id="form1" runat="server">
betway 2        <asp:ScriptManager ID="ScriptManager1" runat="server">
betway 3        </asp:ScriptManager>
betway 4    
betway 5    <script language="javascript" type="text/javascript">
betway 6        Type.registerNamespace("AspNetAjaxOverView"); //注册命名空间
betway 7        //写一个类,=号后为构造方法
betway 8        AspNetAjaxOverView.Person = function(firstName, lastName)
betway 9betway 10        betway 11{
betway 12            this._firstName = firstName;
betway 13            this._lastName = lastName;
betway 14        }
betway 15    //写个属性,get方法以get_开头,set方法同上    AspNetAjaxOverView.Person.prototype = 
betway 16betway 17        betway 18{
betway 19            get_firstName : function()
betway 20betway 21            betway 22{
betway 23                return this._firstName;
betway 24            },
betway 25            get_lastName : function()
betway 26betway 27            betway 28{
betway 29                return this._lastName;
betway 30            },
betway 31            toString : function()
betway 32betway 33            betway 34{//toString覆盖了类的toString方法
betway 35                return String.format("Hello, I'm {0} {1}.",
betway 36                    this.get_firstName(),
betway 37                    this.get_lastName());
betway 38            }
betway 39        }
betway 40    //把这个类注册到命名空间
AspNetAjaxOverView.Person.registerClass("AspNetAjaxOverView.Person");
betway 41    //定义子类    
betway 42        AspNetAjaxOverView.Employee = function(firstName, lastName, title)
betway 43betway 44        betway 45{
betway 46    //继承父类的构造方法
AspNetAjaxOverView.Employee.initializeBase(this, [firstName, lastName]);
betway 47            
betway 48            this._title = title;
betway 49        }
betway 50        AspNetAjaxOverView.Employee.prototype = 
betway 51betway 52        betway 53{
betway 54            get_title : function()
betway 55betway 56            betway 57{
betway 58                return this._title;
betway 59            },
betway 60            toString : function()
betway 61betway 62            betway 63{
betway 64//调用父类中的toString方法
betway 65                return AspNetAjaxOverView.Employee.callBaseMethod(this, "toString")   
betway 66                    " My title is '"   this.get_title()   "'.";
betway 67            }
betway 68        }
betway 69    //注册时第二个参数表明为继承父类
    AspNetAjaxOverView.Employee.registerClass("AspNetAjaxOverView.Employee", AspNetAjaxOverView.Person);
betway 70    </script>

第一部分:客户端页面

Namespace = new Object();
Namespace.register = function(fullname){
try
{
var nsArray = fullname.split(".");
var strNS = "";
var strEval = "";
for(var i=0;i<nsArray.length;i ){
if(strNS.length >0)
strNS = ".";
strNS = nsArray[i];
strEval = " if(typeof(" strNS ") =='undefined') " strNS " = new Object(); ";
}
if(strEval != "") eval(strEval);
}catch(e){alert(e.message);}
}

二.异步通讯类
1.服务器端定义一个C#类
  public class Employee
 {
  private string _FirstName;
  private string _LastName;
  private string _Title;

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="WebApplication1.WebForm3" %>

.Employee.js
Employee.js

  public Employee() { }
  public Employee(string firstName, string lastName, string title)
  public string FirstName
  public string LastName
  public string Title
 }
2.服务器端接收请求的GetEmployee.ashx

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
    <title></title>

复制代码 代码如下:

betway 71betway 72GetEmployee.ashx
betway 73<%@ WebHandler Language="C#" Class="AspNetAjaxOverview.GetEmployee" %>
betway 74
betway 75using System;
betway 76using System.Web;
betway 77using System.Web.Script.Serialization;
betway 78
betway 79namespace AspNetAjaxOverview
betway 80betway 81betway 82{
betway 83    public class GetEmployee : IHttpHandler
betway 84betway 85    betway 86{
betway 87        public void ProcessRequest(HttpContext context)
betway 88betway 89        betway 90{
betway 91            context.Response.ContentType = "text/plain";
betway 92            //从客户端获取Request参数
betway 93            string firstName = context.Request.Params["firstName"];
betway 94            string lastName = context.Request.Params["lastName"];
betway 95            string title = context.Request.Params["title"];
betway 96            Employee employee = new Employee(firstName, lastName, title);
betway 97            //创建Javascript序列化实例
betway 98            JavaScriptSerializer serializer = new JavaScriptSerializer();
betway 99            string jsonEmp = serializer.Serialize(employee);//把C#实例Javascript序列化
betway 100            //把C#实例发送到客户端
betway 101            context.Response.Write(jsonEmp);
betway 102        }
betway 103
betway 104        public bool IsReusable
betway 105betway 106        betway 107{
betway 108            get
betway 109betway 110            betway 111{
betway 112                return false;
betway 113            }
betway 114        }
betway 115
betway 116    }
betway 117}

    <script src="jquery-1.3.2-vsdoc.js" type="text/javascript"></script>

//注册命名空间
Namespace.register("MyCompany");
//1.类:雇员
MyCompany.Employee = function(empName){
this.Name = empName;
this.Salary = 1000;
this.Position = "cleaner";
}
MyCompany.Employee.prototype.ShowName = function(){
return "I'm " this.Name ",my salary is $" this.Salary;
}
MyCompany.Employee.prototype.Work = function(){
return "I'm a " this.Position ",I'm cleaning all day!"
}
//2.类:程序员
MyCompany.Developer = function(empName){
//继承父类属性
MyCompany.Employee.call(this,empName);
//覆盖父类属性
this.Position = "developer";
//扩展属性
this.Technology = "C#";
}
//继承父类原型方法
MyCompany.Developer.prototype = new MyCompany.Employee();
//覆盖父类方法
MyCompany.Developer.prototype.Work = function(){
return "I'm a " this.Position ",i'm good at " this.Technology ",i'm coding all day!"
}

3.客户端调用这个类

    <script src="json2.js" type="text/javascript"></script>

测试代码

betway 118betway 119Code
betway 120<script language="javascript" type="text/javascript">
betway 121    function showEmployee(firstName, lastName, title)
betway 122betway 123    betway 124{  //创建Request实例
betway 125        var request = new Sys.Net.WebRequest();
betway 126        request.set_url('GetEmployee.ashx'); //请求到GetEmployee.ashx
betway 127        request.set_httpVerb("POST");//请求方式
betway 128        request.add_completed(onGetEmployeeComplete);//添加回调函数到Request实例
betway 129        
betway 130        var requestBody = String.format(
betway 131            "firstName={0}&lastName={1}&title={2}",
betway 132            encodeURIComponent(firstName),//转义为可请求URI格式
betway 133            encodeURIComponent(lastName),
betway 134            encodeURIComponent(title));
betway 135        request.set_body(requestBody);//添加到Request参数集
betway 136        
betway 137        request.invoke();//发送请求
betway 138    }
betway 139    //回调函数定义
betway 140    function onGetEmployeeComplete(response)
betway 141betway 142    betway 143{//response.get_responseAvailable():Response是否有可用回复
betway 144        if (response.get_responseAvailable())
betway 145betway 146        betway 147{
betway 148            var employee = response.get_object();//接收服务器端实例
betway 149            alert(String.format(
betway 150                "Hello I'm {0} {1}, my title is '{2}'",
betway 151                employee.FirstName,//使用服务器端实例的属性
betway 152                employee.LastName,
betway 153                employee.Title));
betway 154        }
betway 155    }
betway 156</script>

    <script type="text/javascript">
        $(function() {
            //构造一个json对象,很类似于C#中的匿名类型
            var employee = {
                Name: "chenxizhang",
                Country: "China",
                Orders: [
                    { OrderID: 10248 },
                    { OrderID: 10249 }
                ]
            };

复制代码 代码如下:

三.客户端调用Webservice
1.服务器端Webservice

            //发送POST请求,数据也是json格式。但数值部分需要转换为字符串
            $.post("EmployeeHandler.ashx", { data: JSON.stringify(employee) }, function(result) {
                var r = JSON.parse(result);
                alert(r.Message);
            });
        });
    </script>

<html>
<title>javascript 面向对象的实现 namespace,class,继承,重载</title>
<head>
<script language="javascript" src="namespace.js" type="text/javascript"></script>
<script language="javascript" src="employee.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
    function showEmployee(){                
        var emp = new MyCompany.Employee("xiaoming");
        showInfo(emp);
    }
    function showDeveloper(){
        var emp = new MyCompany.Developer("Gates");
        showInfo(emp);
    }    
    function showInfo(emp){
        alert(emp.ShowName());
        alert(emp.Work());
    }
</script>
</head>
<body>
<input type="button" value="show employee info" onclick="showEmployee();"/><br/><br/>
<input type="button" value="show developer info" onclick="showDeveloper();"/>
</body>
</html>

betway 157namespace AspNetAjaxOverview
betway 158betway 159betway 160{
betway 161    [WebService(Namespace = "]
betway 162    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
betway 163    [ScriptService] //允许客户端调用的类标记(必须)
betway 164    public class EmployeeService : System.Web.Services.WebService
betway 165betway 166    betway 167{
betway 168        [WebMethod]
betway 169        [ScriptMethod]  //允许客户端调用的方法标记(必须)
betway 170        public Employee GetEmployee(string firstName, string lastName, string title)
betway 171betway 172        betway 173{
betway 174            return new Employee(firstName, lastName, title);
betway 175        }
betway 176    }
betway 177}

</head>
<body>
    <form id="form1" runat="server">
    <div>
    </div>
    </form>
</body>
</html>

源代码打包下载

2.客户端调用

第二部分:ashx部分

...

betway 178<asp:ScriptManager ID="ScriptManager1" runat="server">
betway 179    <Services>
betway 180    <!--为ScriptManager指定WebService服务器端程序,会自动生成客户端代理-->
betway 181        <asp:ServiceReference Path="EmployeeService.asmx" />
betway 182    </Services>
betway 183</asp:ScriptManager>
betway 184
betway 185<script language="javascript" type="text/javascript">
betway 186    function showEmployee(firstName, lastName, title)
betway 187betway 188    betway 189{//在这里就可以直接调用WebServic方法了
betway 190        AspNetAjaxOverview.EmployeeService.GetEmployee(
betway 191            firstName,
betway 192            lastName,
betway 193            title,
betway 194            onGetEmployeeSuccess);
betway 195    }
betway 196    //回调函数参数为服务器端类实例,通过代理可直接使用
betway 197    function onGetEmployeeSuccess(employee)
betway 198betway 199    betway 200{
betway 201        alert(String.format(
betway 202            "Hello I'm {0} {1}, my title is '{2}'",
betway 203            employee.FirstName,
betway 204            employee.LastName,
betway 205            employee.Title));
betway 206    }
betway 207</script>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.IO;
using System.Text;
//必须添加System.ServiceModel.Web和System.Runtime.Serialization的引用
namespace WebApplication1
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class EmployeeHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            var ser = new DataContractJsonSerializer(typeof(Employee));
            var data = context.Request["data"];
            var ms = new MemoryStream(Encoding.UTF8.GetBytes(data));
            var emp = (Employee)ser.ReadObject(ms);
            ms.Close();
            //此时已经得到了相应的Employee实例,可以进行服务器端的处理

 

            var ser2 = new DataContractJsonSerializer(typeof(ActionResult));
            var ms2 = new MemoryStream();
            var result = new ActionResult() { Code = 200, Message = "成功" };
            ser2.WriteObject(ms2, result);
            ms2.Position = 0;
            var buffer = new byte[ms2.Length];
            ms2.Read(buffer, 0, buffer.Length);
            ms2.Close();
            context.Response.Write(Encoding.UTF8.GetString(buffer));

            //返回结果

           
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

    [DataContract]
    public class Employee {
        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public string Country { get; set; }

        [DataMember]
        public OrderItem[] Orders { get; set; }

    }
    [DataContract]
    public class OrderItem
    {
        [DataMember]
        public int OrderID { get; set; }
    }

    [DataContract]
    public class ActionResult
    {
        [DataMember]
        public int Code { get; set; }
        [DataMember]
        public string Message { get; set; }
   
    }
}

第三部分:进一步的优化,编写两个扩展方法(这是C# 3.0的新特性)    /// <summary>
    /// 这个类型实现了对JSON数据处理的一些扩展方法
    /// </summary>
    public static class JsonExtensions
    {
        /// <summary>
        /// 根据一个字符串,进行JSON的反序列化,转换为一个特定类型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <returns></returns>
        public static T ToJsonObject<T>(this string data) {
            var serializer = new DataContractJsonSerializer(typeof(T));
            var ms = new MemoryStream(
                Encoding.UTF8.GetBytes(data));

            var result = (T)serializer.ReadObject(ms);
            ms.Close();
            return result;
        }
        /// <summary>
        /// 将任何一个对象转换为JSON字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToJsonString<T>(this T obj) {
            var serializer = new DataContractJsonSerializer(typeof(T));
            var ms = new MemoryStream();
            serializer.WriteObject(ms, obj);
            ms.Position = 0;
            var result = Encoding.UTF8.GetString(ms.GetBuffer());
            ms.Close();
            return result;
        }
    } 这样,在ashx里面的代码就很简单了            var emp = context.Request["data"].ToJsonObject<Employee>();
            var result = new ActionResult() { Code = 200, Message = "成功" };
            context.Response.Write(result.ToJsonString());
不错吧,这样以后处理Json就是如此容易

通过Json来传递数据,可以避免以前用传统的post或者get方面拼接字符串中的麻烦

 

本文由必威发布于Web前端,转载请注明出处:ajax学习笔记,面向对象