Show toolbar

2014年1月20日 星期一

Dynamic Post with Iframe

標題:在JavaScript使用虛擬form送出post並以iframe讀取text
JavaScript (index.html):
<button id="test">test</button>
<div id="show">show</div>
<script type="text/javascript">
function $(id) {
    switch(id.substr(0,1)) {
        case '#':
            return document.getElementById(id.substr(1));
        case '.':
            var elems = document.body.getElementsByTagName('*');
            var target = id.substr(1);
            var result=[];
            for(i=0;j=elems[i];i++) {
                if((j.className).indexOf(target)!=-1) result.push(j);
            }
            return result;
        default:
            return document.getElementsByTagName(id);
    }
}
var loadpost = {
    current : null,
    queue : [],
    request : function(q) {
        //Create iframe
        try { //IE
            var iframe = document.createElement('<iframe name="loadboxy">');
        } catch (e) {
            var iframe = document.createElement('iframe');
        }
        iframe.style.display = 'none';
        iframe.name = 'loadboxy';
        iframe.id = 'loadboxy';
        if(iframe.attachEvent) {
            iframe.attachEvent("onload", function(){
                loadpost.load();
            });
        } else {
            iframe.onload = function(){
                loadpost.load();
            };
        }
        //Create form
        var form = document.createElement('form');
        form.target = 'loadboxy';
        form.action = q.url;
        form.method = 'post';
        form.style.display = 'none';
        for(var key in q.param) {
            if(q.param[key].constructor == Array) {
                for(var i=0;i<q.param[key].length;i++) {
                    var input = document.createElement('input');
                    input.type = 'hidden';
                    input.name = key;
                    input.value = q.param[key][i];
                    form.appendChild(input);
                }
            } else {
                var input = document.createElement('input');
                input.type = 'hidden';
                input.name = key;
                input.value = q.param[key];
                form.appendChild(input);
            }
        }
        //Queue
        this.queue.push({
            form : form,
            iframe : iframe,
            flag : 0,
            load : q.load
        });
        if (!this.current) this.action();
    },
    task : function() {
        var iFrame = this.current.iframe;
        var iFrameBody;
        if (iFrame.contentDocument) //FF
            iFrameBody = iFrame.contentDocument.getElementsByTagName('body')[0];
        else if (iFrame.contentWindow) //IE
            iFrameBody = iFrame.contentWindow.document.getElementsByTagName('body')[0];
        this.current.load(iFrameBody.innerHTML);
    },
    load : function() {
        if(this.current.flag == 1) {
            this.task();
            $('body')[0].removeChild(this.current.iframe);
            $('body')[0].removeChild(this.current.form);
            this.action();
        } else {
            this.current.flag = 1;
            this.send();
        }
    },
    action : function() {
        this.current = null;
        if(this.queue.length) {
            this.current = this.queue.shift();
            $('body')[0].appendChild(this.current.iframe);
        }
    },
    send : function() {
        $('body')[0].appendChild(this.current.form);
        this.current.form.submit();
    }
};
$('#test').onclick = function() {
    loadpost.request({
        url : "action.php",
        param : {
            'num1' : 10,
            'num2' : 20,
            'num[]' : new Array(30, 40)
        },
        load : function(data) {
            $('#show').innerHTML = data;
        }
    });
};
</script>
PHP (index.php):
<?php
$num1 = !empty($_POST['num1']) ? $_POST['num1'] : null;
$num2 = !empty($_POST['num2']) ? $_POST['num2'] : null;
$num3 = rand(0,10);
$num = !empty($_POST['num']) ? $_POST['num'] : null;
$sum = 0;
foreach($num as $value) {
    $sum += $value;
}
$total = $num1 + $num2 + $num3 + $sum;
echo $num1."+".$num2."+".$num3."+".$sum."=".$total;
?>

說明:
使用純JavaScript動態在Head產生Iframe及在Body產生Form送出Post後,呼叫函式取得Text資料。

2013年10月18日 星期五

Fluent Interface with Prototype

標題:流暢介面搭配Prototype屬性的用法
JavaScript (index.html):
<span id="fatty"></span> V.S. <span id="thin"></span>
<script type="text/javascript">
var Runner = function(e) {
    this.speed = e.speed; //Meters per second
    this.time = null; //Second
    this.distance = null; //Meter
};

Runner.prototype.ready = function(e) {
    this.time = 0; //Cost time
    this.distance = e.starting; //Starting point
    return this;
};

Runner.prototype.run = function(e) {
    this.time += e.second;
    this.distance += this.speed * e.second; // Distance = Speed * Time
    return this;
};

Runner.prototype.halt = function(e) {
    this.time += e.second;
    return this;
};

Runner.prototype.result = function(e) {
    document.getElementById(e.id).innerHTML = "Distance:" + this.distance + " m, Cost time:" + this.time + " sec";
    return this;
};

var fatty = new Runner({speed:2}); //Speed: 2m/s
fatty.ready({starting:10}).run({second:30}).halt({second:5}).run({second:15}).result({id:"fatty"});

var thin = new Runner({speed:2.5}); //Speed: 2.5m/s
thin.ready({starting:0}).run({second:40}).result({id:"thin"});
</script>

範例結果:
V.S.

說明:
此程式使用流暢介面搭配Prototype屬性的方式撰寫,
計算胖與瘦的人100公尺跑步的時間(不計加減速),
條件項目:
1. 胖者速度為每秒2公尺 - Runner({speed:2})
2. 瘦者速度為每秒2.5公尺 - Runner({speed:2.5})
3. 瘦者禮讓胖者由10公尺處起跑 - ready({starting:10})
4. 胖者跑了30秒以後,休息了5秒,再繼續跑了15秒 - run({second:30}).halt({second:5}).run({second:15})
5. 瘦者跑了40秒全程無休息 - run({second:40})

2013年10月17日 星期四

Positive and Countdown Timer

標題:正倒數計時器
JavaScript (index.html):
<span id="loveboxy"></span>
<script type="text/javascript">
var TimerBoxy = function(e) {
    this.id = e.id;
    this.target = new Date(e.target);
};
TimerBoxy.prototype.show = function() {
    var s = Math.abs(parseInt( (new Date().getTime() - this.target.getTime() )/1000,10));
    var m = s/60;
    var h = m/60;
    var D = h/24;
    document.getElementById(this.id).innerHTML = 
    parseInt(D,10) + "日" + parseInt(h%24,10) + "時" + parseInt(m%60,10) + "分" + parseInt(s%60,10) + "秒";
};
TimerBoxy.prototype.start = function() {
    if(!this.timer) {
        var that = this;
        this.show();
        this.timer = window.setInterval(function() {
            that.show();
        }, 1000);
    }
};
TimerBoxy.prototype.stop = function() {
    if(this.timer) {
        window.clearInterval(this.timer);
        this.timer = null;
    }
};
loveboxy = new TimerBoxy({
    id : "loveboxy",
    target : "2011/11/11 11:11:11"
});
loveboxy.start();
</script>
使用範例:


說明:
當目標時間小於當日時間則為正數計時,反之則為倒數計時。
(感謝TonyQ幫忙修正。)

2013年10月8日 星期二

Send Mail with Google Form

標題:Google表單指令碼寄信
Google App Script (sendmail.gs):
function sendmail(e) {
    var currentItemResponses = e.response.getItemResponses();
    var name = currentItemResponses[0].getResponse(); //姓名
    var sex = currentItemResponses[1].getResponse();  //性別
    var mail = currentItemResponses[2].getResponse(); //E-MAIL
    var sexword = (sex=="男")?"先生":"小姐";
    MailApp.sendEmail(mail, "報名成功", name + " " + sexword + "您好,\n" + "恭喜您報名成功。");
}

說明:
用於在表單新增寄信的指令碼。

2013年10月3日 星期四

Folder Access Restrictions in Node.JS

標題:Express資料夾權限控制
Node.JS (main.js):

說明:
使用Express搭配Session的方式進行私用資料夾的權限控制。