一共有 24 篇文章,分页:3 / 5

Mini Ajax is a Lightweight Javascript AJAX library

来源:https://code.google.com/p/miniajax/

非常棒的一个迷你ajax库!

HOW TO USE:

ajax.x - The XMLHttpRequest object (or MS equivalent) used for communication

ajax.serialize(f) f = the form element you wish to be serialized This function serializes all the fields in a form so that they can be passed as a query string in the form 'arg1=val1&arg2=val2'.

ajax.get(url, func) url = the url to query (can contain arguments after a '?') func = the function to call once the response is returned This function uses a GET request to query the specified url and return a response to the specified function.

ajax.gets(url) url = the url to query (can contain arguments after a '?') This function uses a GET request to query the specified url and return a response synchronously. Use this sparingly, as synchronous calls can lock up the browser.

ajax.post(url, func, args) url = the url to query func = the function to call once the response is returned args = a string containing arguments to be passed to the url This function uses a POST request to query the specified url and return a response to the specified function.

ajax.update(url, elm) url = the url to query elm = the (name of the) element to update This function uses a GET request to query the specified url and insert the result into the specified element.

ajax.submit(url, elm, frm) url = the url to query elm = the (name of the) element to update frm = the form element to submit This function is typically used in the onsubmit handler of a function. The form is not submitted the usual way; the form is instead serialized using 'ajax.serialize' and submitted using 'ajax.post'. The result is then inserted into the specified element.

SOURCE CODE:

function $(e){if(typeof e=='string')e=document.getElementById(e);return e}; function collect(a,f){var n=[];for(var i=0;i<a.length;i++){var v=f(a[i]);if(v!=null)n.push(v)}return n};

ajax={}; 
ajax.x=function(){try{return new ActiveXObject('Msxml2.XMLHTTP')}catch(e){try{return new ActiveXObject('Microsoft.XMLHTTP')}catch(e){return new XMLHttpRequest()}}}; 
ajax.serialize=function(f){var g=function(n){return f.getElementsByTagName(n)};var nv=function(e){if(e.name)return encodeURIComponent(e.name)+'='+encodeURIComponent(e.value);else return ''};var i=collect(g('input'),function(i){if((i.type!='radio'&&i.type!='checkbox')||i.checked)return nv(i)});var s=collect(g('select'),nv);var t=collect(g('textarea'),nv);return i.concat(s).concat(t).join('&');}; 
ajax.send=function(u,f,m,a){var x=ajax.x();x.open(m,u,true);x.onreadystatechange=function(){if(x.readyState==4)f(x.responseText)};if(m=='POST')x.setRequestHeader('Content-type','application/x-www-form-urlencoded');x.send(a)}; 
ajax.get=function(url,func){ajax.send(url,func,'GET')}; 
ajax.gets=function(url){var x=ajax.x();x.open('GET',url,false);x.send(null);return x.responseText}; 
ajax.post=function(url,func,args){ajax.send(url,func,'POST',args)}; 
ajax.update=function(url,elm){var e=$(elm);var f=function(r){e.innerHTML=r};ajax.get(url,f)}; 
ajax.submit=function(url,elm,frm){var e=$(elm);var f=function(r){e.innerHTML=r};ajax.post(url,f,ajax.serialize(frm))};

Object、Array、Vector遍历性能测试

talk is cheap,show me the code!

var obj:Object = { }; 
var arrVector:Vector.<int> = new Vector.<int>(); 
var arrArray:Array = []; 

var len:int; 
var i:int; 
var key:String; 
var val:int; 
var t1:int, t2:int, t3:int, t4:int, t5:int, t6:int, t7:int, t8:int, t9:int,t10:int; 
var t11:int, t12:int, t13:int, t14:int, t15:int, t16:int, t17:int, t18:int, t19:int; 

//初始化50万个元素 
t1 = getTimer(); 
for (i = 0; i < 500000; i++)  
{ 
    obj[i] = i; 
    arrVector.push(i); 
    arrArray.push(i); 
} 
//for遍历key 
t2 = getTimer(); 
for (key in obj) 
{ 
    val = obj[key]; 
} 
//for each 遍历value 
t3 = getTimer(); 
for each(val in obj) 
{ 
    val; 
} 
//for each 遍历Vector 
t4 = getTimer(); 
for each(val in arrVector) 
{ 
    val; 
} 
//for循环Vector,length属性放for里面 
t5 = getTimer(); 
for (i = 0; i < arrVector.length; i++)  
{ 
    val = arrVector[i]; 
} 
//for循环Vector,length属性放for外面 
t6 = getTimer(); 
len = arrVector.length; 
for (i = 0; i < len; i++)  
{ 
    val = arrVector[i]; 
} 
//for each遍历Vector 
t7 = getTimer(); 
for each(val in arrVector) 
{ 
    val; 
} 
//for循环Array,length属性放for里面 
t8 = getTimer(); 
for (i = 0; i < arrArray.length; i++)  
{ 
    val = arrArray[i]; 
} 
//for循环Array,length属性放for外面 
t9 = getTimer(); 
len = arrArray.length; 
for (i = 0; i < len; i++)  
{ 
    val = arrArray[i]; 
} 
t10 = getTimer(); 

trace("1:" + (t2-t1));//288 
trace("2:" + (t3-t2));//1974 
trace("3:" + (t4-t3));//67 
trace("4:" + (t5-t4));//50 
trace("5:" + (t6-t5));//44 
trace("6:" + (t7-t6));//42 
trace("7:" + (t8-t7));//52 
trace("8:" + (t9-t8));//70 
trace("9:" + (t10-t9));//46

可以看出for遍历object获得key,然后再用obj[key]获得value的方式性能是最低的!

用Vector,然后把length提前赋值出来,再for循环是最快的!

补充:根据这篇文章 http://jacksondunstan.com/articles/2514 的测试结果,在使用for in循环时,不指定key的类型,比定义string类型的key,快5倍:

// 慢! 
for (var str:String in obj) 
{ 
} 

// 比上面那种方式快 5 倍! 
for (var key:* in obj) 
{ 
}

exbuffer.c——纯C写的TCP中的粘包、分包问题的解决方案

设计目标是一个纯C的网络协议缓冲器,该协议简单介绍:

协议包分为包头和包体:包长采用2个字节或者4个字节,用来表示本次数据包中包体的长度

接受到数据就存储在缓冲区,缓冲区动态扩展以保证可以足够存储。

当接收到一个以上完整的数据包就调用回调函数recvHandle。

项目托管页面:https://github.com/play175/exbuffer.c

另外有nodejs版本的exbuffer:https://github.com/play175/ExBuffer

对C不熟悉,第一次写C代码,可能很多不合理的地方,欢迎批评指正!

附使用代码:

#include "exbuffer.c" 

void recvHandle(unsigned char *rbuf,size_t len) 
{ 
    printf("收到数据:%d\n",len); 
    exbuffer_printHex(rbuf,len); 
} 

int main(int argc, char **argv) 
{ 
    exbuffer_t* value; 
    value = exbuffer_new(); 
    value->recvHandle = recvHandle; 

    unsigned char buf[] = {0,2,3,4,0,1,5,0}; 
    exbuffer_put(value,(unsigned char*)buf,0,8); 

    unsigned char buf2[] = {3}; 
    exbuffer_put(value,(unsigned char*)buf2,0,1); 

    unsigned char buf3[] = {6,6,6}; 
    exbuffer_put(value,(unsigned char*)buf3,0,3); 

    //printf("有效数据长度:%d\n",exbuffer_getLen(value)); 
    //printf("缓冲区长度:%d\n",value->bufferlen); 
    printf("缓冲区:\n"); 
    exbuffer_dump(value); 
    exbuffer_free(&value); 

    //getchar(); 
    return EXIT_SUCCESS; 
}

AS3的原型:prototype

写过JS的都清楚原型:prototype,AS3也有这个机制,不多说,直接上代码:

//给数组原型增加一个获取随机数组元素的方法:randomItem 
Array.prototype.getRandomItem = function(): * 
{ 
    return this[Math.floor(Math.random() * this.length)]; 
}; 

//这里设置这个方法不可被(for...in、foreach...in)枚举,非常重要! 
Array.prototype.setPropertyIsEnumerable('getRandomItem', false); 

var arr:Array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 
trace(arr.getRandomItem());

虽然看起来原型也牛逼,可以直接在运行时赋予某个对象一个功能函数,但是也因为如此我们在写代码的时候并不一定知道这个对象有个方法,由此给代码结构带来混乱,所以一般还是不要去扩展原型。

当然总有原型的用武之地,之前看到有人利用原型机制对as代码进行加密解密来保护代码安全。

AS3使用自定义元数据标记,类似C#的类属性、成员属性

在AS3 使用元数据标签最多的应该是swf标签了,如:

[SWF(backgroundColor = 0x000000, frameRate = 24, width = 1000, height = 600)]

那么能不能自定义我们自己的标签,然后在运行时,获取那些含有自定义标签的类或者类成员,然后达到注入的目的呢?答案是肯定的,在robotleg等一些开源框架中也用到了注入。

要是有元数据标签需要在编译器的扩展参数中指定-keep-as3-metadatac参数:

-keep-as3-metadata+=Inject,BindData

后面的Inject、BindData就是下面的例子要用的两个标签

需要注意的是这个编译参数只需要在一个运行库中指定即可,比如我们使用swc,那么编译这个swc指定了-keep-as3-metadatac参数,那么在使用swc的库的项目是不需要再指定的。在-keep-as3-metadatac参数使用“+=”是为了避免把别的参数定义覆盖掉。

比如Test1.as类使用元标签:

package 
{ 
    /** 
     * ... 
     * @author yoyo 
     */ 
    [Inject]      
    public class Test1 
    { 
        [BindData(param1="abc")] 
        public var s:String = 'ssss'; 

        public function Test1() 
        { 
        } 

    } 

};

接下来我们做注入操作,在不需要直接引用s成员的情况下,根据BindDta标签,修改这个成员变量的值:

package 
{ 
    import flash.display.Sprite; 
    import flash.events.Event; 
    import flash.utils.describeType; 
    import flash.xml.XMLNode; 

    /** 
     * ... 
     * @author yoyo 
     */ 
    public class Main extends Sprite 
    { 

        public function Main():void 
        { 
            if (stage) 
                init(); 
            else 
                addEventListener(Event.ADDED_TO_STAGE, init); 
        } 

        private function init(e:Event = null):void 
        { 
            removeEventListener(Event.ADDED_TO_STAGE, init); 
            // describeType方法返回的信息类似下面的xml 
            /** 
               <type name="Test1" base="Object" isDynamic="false" isFinal="false" isStatic="false"> 
               <extendsClass type="Object"/> 
               <variable name="s" type="String"> 
               <metadata name="BindData"> 
               <arg key="param1" value="abc"/> 
               </metadata> 
               <metadata name="__go_to_definition_help"> 
               <arg key="pos" value="131"/> 
               </metadata> 
               </variable> 
               <metadata name="Inject"/> 
               <metadata name="__go_to_ctor_definition_help"> 
               <arg key="pos" value="173"/> 
               </metadata> 
               <metadata name="__go_to_definition_help"> 
               <arg key="pos" value="79"/> 
               </metadata> 
               </type> 

             */ 

            var t:Test1 = new Test1();   

            initMeta(t); 

            trace(t.s);//打印修改后的值 
        } 

        /** 
         * 开始对这个对象进行注入 
         * @param   obj 
         */ 
        private function initMeta(obj:*):void 
        { 
            var xml:XML = describeType(obj); 

            var typeName:String = xml.@name; 

            initClassMeta(obj,typeName,xml); 

            for (var i:int = 0, len:int = xml.variable.length(); i < len;i++) 
            { 
                var variables:XML = xml.variable[i]; 

                initVariableMeta(obj,typeName,variables); 
            } 
        } 

        /** 
         * 获取含有自定义标签的类对象 
         * @param   xml 
         */ 
        private function initClassMeta(obj:*,typeName:String,xml:XML):void 
        { 
            for (var i:int = 0, len:int = xml.metadata.length(); i < len;i++) 
            { 
                var mata:XML = xml.metadata[i]; 
                var metaName:String = mata.@name; 
                switch (metaName) 
                { 
                    case 'Inject': 
                        trace(typeName + ',Inject:' + metaName); 
                        break; 
                } 
            } 
        } 

        /** 
         * 获取含有自定义标签的成员变量 
         * @param   xml 
         */ 
        private function initVariableMeta(obj:*,typeName:String,xml:XML):void 
        { 
            var name:String = xml.@name; 
            var type:String = xml.@type; 
            for (var i:int = 0, len:int = xml.metadata.length(); i < len;i++) 
            { 
                var mata:XML = xml.metadata[i]; 
                var metaName:String = mata.@name; 
                switch (metaName) 
                { 
                    case 'BindData': 
                        trace(typeName + ',BindData:' + metaName + '(' + mata.arg[0].@value + ')'); 
                        obj[name] = 'inject';//修改这个成员变量的值 
                        break; 
                } 
            } 
        } 

    } 
}