Show toolbar

2014年3月11日 星期二

Dynamic get jsonp

標題:動態取得Jsonp資料
JavaScript (index.html):
<div id="output_getjsonp"></div>
<script type="text/javascript">
var getjsonp = function() {
    this.head = document.getElementsByTagName('head')[0] || document.documentElement;
    this.current = null;
    this.queue = [];
};
getjsonp.prototype.request = function(q) {
    var fid = (q.fid||'_getjsonp') + new Date().getTime();
    console.log(fid);
    var script = document.createElement('script');
    script.src = q.url.replace('callback=?', 'callback=' + fid);
    this.queue.push({
        fid : fid,
        script : script,
        load : q.load
    });
    if(!this.current) this.action();
};
getjsonp.prototype.action = function() {
    var self = this;
    this.current = null;
    if(this.queue.length) {
        this.current = this.queue.shift();
        window[this.current.fid] = function(data) {
            self.head.removeChild(self.current.script);
            self.current.load && self.current.load(data);
            self.action();
        };
        this.head.appendChild(this.current.script);
    }
};

var jsonp = new getjsonp();
jsonp.request({
    fid : '_myjsonp',
    url : 'http://codeboxy.blogspot.com/feeds/posts/default?alt=json&callback=?',
    load : function(data) {
        document.getElementById('output_getjsonp').innerHTML = data.feed.entry[0].title.$t;
    }
});
</script>

範例結果:

說明:
動態使用jsonp取得json資料,測試支援版本:
  • Google Chrome 33.0.1750.146 m
  • Firefox 27.0.1
  • IE 11.0.9600.16518

2014年3月10日 星期一

JavaScript Advanced Logical Operators

標題:JavaScript邏輯運算子進階用法
JavaScript (main.js):
function foo() {
    console.log('Hello');
    return true;
}
function bar() {
    console.log('World');
    return false;
}
foo() && bar(); //Hello World
bar() && foo(); //World
foo() || bar(); //Hello
bar() || foo(); //World Hello

說明:
1. foo()為true 則會繼續執行bar()
2. bar()為false不會繼續執行foo()
3. foo()為true 不會繼續執行bar()
4. bar()為false則會繼續執行foo()

2014年3月6日 星期四

Fluent Interface in exports of Node.js

標題:Node.js的exports使用流暢介面寫法
Node.js (main.js):
var my = require('./count.js');
var foo = new my.foo(10, 2);
foo.plus().say();
foo.times().say();
exports js (count.js):
var foo = function(m, n) {
    this.m = m;
    this.n = n;
    this.answer = 0;
    this.method = "";
};

foo.prototype.plus = function() {
    this.answer = this.m + this.n;
    this.method = "+";
    return this;
};

foo.prototype.times = function() {
    this.answer = this.m * this.n;
    this.method = "*";
    return this;
};

foo.prototype.say = function() {
    console.log("%d %s %d = %d", this.m, this.method, this.n, this.answer);
    return this;
};

exports.foo = foo;
範例結果:


說明:
在Node.js中採用流暢介面寫法,並使用exports建立一個外部js,在主程式中require後使用。

2014年2月27日 星期四

File upload problem solving in Connect 3.0

標題:解決Connect 3.0檔案上傳的問題
Node.js (main.js):
/*
Connect 3.0 的 connect.multipart() 將被移除,
可使用 multiparty 解決向下相容,方法如下:

1. 安裝multiparty
npm install multiparty

2. 安裝connect-multiparty
npm install connect-multiparty

3. 安裝qs (因 connect-multiparty 需要用到)
npm install qs

4. 建立一個uploads資料夾

By QQBoxy
*/
var express  = require('./node_modules/express'),
    multiparty = require('./node_modules/multiparty'),
    multipart  = require('./node_modules/connect-multiparty'),
    fs         = require('fs');

var multipartMiddleware = multipart();

var app = express();
var port = 1337;
app.listen(port);

app.post('/uploads', multipartMiddleware, function(req, res) {
    fs.readFile(req.files.myfile.path, function (err, data) { //fs讀檔
        var newPath = __dirname + "/uploads/" + req.files.myfile.originalFilename; //指派新路徑
        fs.writeFile(newPath, data, function (err) { //fs寫檔
            console.log(req.files);
            res.send(req.files);
        });
    });
});

app.get('/', function (req, res) {
    res.send( //表單
        '<form action="/uploads" enctype="multipart/form-data" method="post">'+
        '<input type="file" name="myfile" multiple="multiple"><br />'+
        '<input type="submit" value="Upload">'+
        '</form>'
    );
});

console.log("Start express server");

說明:
Connect 3.0 的 connect.multipart() 將被移除,可使用 multiparty 解決向下相容的問題。

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資料。