Show toolbar
顯示具有 custom 標籤的文章。 顯示所有文章
顯示具有 custom 標籤的文章。 顯示所有文章

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年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年4月12日 星期五

Dynamic Read Text with Iframe

標題:在JavaScript使用Iframe讀取Text
JavaScript (index.html):
<button id="test">Click Me</button>
<script type="text/javascript">
var iframeboxy = {
    current : null,
    queue : [],
    request : function(q) {
        var iframe = document.createElement("iframe");
        iframe.style.display = "none";
        iframe.name = "iframeboxy";
        iframe.src = q.url;
        if(iframe.attachEvent) { //IE
            iframe.attachEvent("onload", function() {
                iframeboxy.callback(iframe);
            });
        } else {
            iframe.onload = function() {
                iframeboxy.callback(this);
            };
        }
        this.queue.push({
            iframe : iframe,
            data : q.data
        });
        if (!this.current) this.action();
    },
    action : function() {
        this.current = null;
        if(this.queue.length) {
            this.current = this.queue.shift();
            document.getElementsByTagName("body")[0].appendChild(this.current.iframe);
        }
    },
    callback : function(e) {
        this.current.data((e.contentDocument) ? e.contentDocument : e.contentWindow.document);
        document.getElementsByTagName("body")[0].removeChild(this.current.iframe);
        this.action();
    }
};

document.getElementById("test").onclick = function() {
    iframeboxy.request({
        url : "robots.txt",
        data : function(e) {
            alert(e.documentElement.getElementsByTagName("pre")[0].innerHTML);
        }
    });
};
</script>

範例結果:


說明:
使用純JavaScript動態在Head產生Iframe後,呼叫函式取得Text資料。 支援Chrome、FireFox、IE10,由於Browser本身限制僅能讀取Local檔案。

2013年1月31日 星期四

C# WPF Confirm Options

標題:使用ShowDialog顯示Confirm視窗並回傳RadioButton的Option名稱
XAML (MainWindow.xaml):
<Window x:Class="WPFConfirmOptions.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="100" Width="200">
    <Grid>
        <Button Content="Confirm Option" Name="confirmBtn" Click="confirmBtn_Click" />
    </Grid>
</Window>

C# (MainWindow.xaml.cs):
using System;
using System.Windows;
using System.Collections.Generic; //List

namespace WPFConfirmOptions
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void confirmBtn_Click(object sender, RoutedEventArgs e)
        {
            var options = new List<Confirm.Option>();
            options.Add(new Confirm.Option
            {
                Name = "Test1",
                Description = "Test Description 1."
            });
            options.Add(new Confirm.Option
            {
                Name = "Test2",
                Description = "Test Description 2."
            });
            options.Add(new Confirm.Option
            {
                Name = "Test3",
                Description = "Test Description 3."
            });
            options.Add(new Confirm.Option
            {
                Name = "Test4",
                Description = "Test Description 4."
            });
            options.Add(new Confirm.Option
            {
                Name = "Test5",
                Description = "Test Description 5."
            });
            Confirm confirm = new Confirm("Confirm", "Hello World", options);
            confirm.ShowDialog();
            if (confirm.DialogResult.HasValue && confirm.DialogResult.Value)
            {
                System.Windows.MessageBox.Show(confirm.CheckedName.ToString());
            }
        }
    }
}

XAML (Confirm.xaml):
<Window x:Class="WPFConfirmOptions.Confirm"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Name="Windows" Title="Confirm" Height="230" Width="300">
    <Grid>
        <TextBlock Height="20" HorizontalAlignment="Center" Margin="0,10,0,0" Name="tbk_StlTypeTitle" Text="Confirm" VerticalAlignment="Top" Width="120" TextAlignment="Center" />
        <GroupBox Header="Options" Margin="0,30,0,50" Name="gbx">
            <Grid Name="OptionsGrid"></Grid>
        </GroupBox>
        <Grid Height="50" Width="240" HorizontalAlignment="Center" VerticalAlignment="Bottom">
            <Button Content="OK" Height="30" Width="100" Name="btn_OK" VerticalAlignment="Center" HorizontalAlignment="Left" Click="btn_OK_Click" />
            <Button Content="Cancel" Height="30" Width="100" Name="btn_Cancel" VerticalAlignment="Center" HorizontalAlignment="Right" Click="btn_Cancel_Click" />
        </Grid>
    </Grid>
</Window>

C# (Confirm.xaml.cs):
using System;
using System.Windows;
using System.Windows.Controls;
using System.Collections.Generic; //List
using System.Linq;

namespace WPFConfirmOptions
{
    /// <summary>
    /// Interaction logic for StlTypeConfirm.xaml
    /// </summary>
    public partial class Confirm : Window
    {
        public Confirm(string header, string message, List<Option> options)
        {
            InitializeComponent();
            this.Header = header;
            this.Message = message;
            this.Options = options;
            AddRadioButton();
        }

        public string Header //Set Head Title
        {
            set
            {
                Windows.Title = value;
            }
        }

        public string Message //Set Content Description
        {
            set
            {
                tbk_StlTypeTitle.Text = value;
            }
        }

        public List<Option> Options;

        public String CheckedName = "";

        public String ResultName
        {
            get
            {
                return CheckedName;
            }
        }

        public class Option
        {
            public string Name { get; set; }
            public string Description { get; set; }
        }

        public void AddRadioButton()
        {
            int key = 0;
            foreach (Option value in Options) // Create Options
            {
                RadioButton radioButton = new RadioButton();
                radioButton.Name = value.Name;
                radioButton.Content = value.Description;
                radioButton.Height = 20;
                radioButton.Width = 250;
                radioButton.Margin = new Thickness(0, (20 + 30 * key), 0, 0);
                radioButton.HorizontalAlignment = HorizontalAlignment.Center;
                radioButton.VerticalAlignment = VerticalAlignment.Top;
                radioButton.IsChecked = false;
                this.OptionsGrid.Children.Add(radioButton);
                this.RegisterName(radioButton.Name, radioButton);
                key++;
            }
            Windows.Height = 200 + 30 * key;
            return;
        }

        private void btn_OK_Click(object sender, RoutedEventArgs e)
        {
            foreach (Option value in Options)
            {
                RadioButton radiobutton = (RadioButton)OptionsGrid.FindName(value.Name);
                if (radiobutton.IsChecked == true)
                {
                    CheckedName = radiobutton.Name;
                    DialogResult = true;
                    return;
                }
            }
            System.Windows.MessageBox.Show("No Select.");
        }

        private void btn_Cancel_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            return;
        }
    }
}

結果:

說明:
使用Add Window方式設計WPF Confirm視窗, 主視窗可設定加入多組選項包含名稱及描述, 並在ShowDialog後的Confirm視窗產生標題、說明及選項, 最後按下確認回傳RadioButton的Option名稱。

2012年3月20日 星期二

Unique Array

標題:陣列過濾重複值
JavaScript (index.html):
function unique(arr) {
    var newArr = [];
    var temp = {};
    for(key in arr) {
        var id = arr[key];
        if(!temp[id] && id != "") {
            newArr.push(id);
            temp[id] = true;
        }
    }
    return newArr;
}
alert(unique(new Array("1","2","4","4","1")));

範例結果:


說明:
簡單過濾掉陣列中重複的數值。

2012年3月7日 星期三

Form iframe virtual load post

標題:虛擬表單送出
JavaScript (inidex.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 (action.php):
<?php
$num1 = !empty($_POST['num1']) ? $_POST['num1'] : null;
$num2 = !empty($_POST['num2']) ? $_POST['num2'] : null;
$total = $num1 + $num2;
echo $num1."+".$num2."=".$total;
?>
說明:
純JavaScript產生虛擬form、iframe並發送POST訊息取得php傳回之內容。

2012年2月11日 星期六

JavaScript dollar sign 2

標題:自定義錢字號函式 2
JavaScript (index.html):
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);
    }
}

說明:
自定義一個錢字號指向id之函式, 繼上篇再加入Class與TagName功能, 讓程式更精簡。

2011年12月11日 星期日

JavaScript dollar sign

標題:自定義錢字號函式
HTML (index.html):
<div id="btn">
    <button>Click1</button>
    <button>Click2</button>
    <button>Click3</button>
</div>
<script type="text/javascript">
    function $(id) {return document.getElementById(id);}
    $('btn').onclick = function(e) {
        e.target.innerHTML = "Clicked";
    };
</script>
範例:

說明:
自定義一個錢字號指向id之函式,讓程式更精簡。

2011年8月4日 星期四

jsonp dynamic

標題:使用jsonp動態取得資料
HTML (index.html):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-TW" xml:lang="zh-TW">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Jsonp dynamic</title>
<script type="text/javascript">
function codeboxy(json) {
    document.getElementById("youtubeTitle").innerHTML = json.entry.title.$t;
}
function getYoutubeTitle() {
    var removeScript = document.getElementById('jsonScript');
    if(removeScript)
        removeScript.parentNode.removeChild(removeScript);
    var yid = document.getElementById('yid').value;
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.id = 'jsonScript';
    script.src = "http://gdata.youtube.com/feeds/api/videos/" + yid + "?alt=json-in-script&callback=codeboxy";
    document.getElementsByTagName('head')[0].appendChild(script);
}
</script>
</head>
<body>
<input type="text" id="yid" value="Sr3hyvjNp94" />
<input type="button" onClick="getYoutubeTitle()" value="Get" />
<div id="youtubeTitle"></div>
</body>
</html>
範例:



說明:
使用純JavaScript動態在Head產生jsonp script後,呼叫函式更新Youtube之Title資料。
支援IE6、FireFox、Chrome。

2011年7月31日 星期日

getCookie

標題:自定義getCookie函式
<script type="text/javascript">
function getCookie(name) {
    var n = name + "=";
    var nlen = n.length;
    var clen = document.cookie.length;
    var i = 0;
    while(i < clen) {
        var j = i + nlen;
        if(document.cookie.substring(i, j) == n) {
            var endstr = document.cookie.indexOf(";", j);
            if(endstr == -1)
                endstr = clen;
            return unescape(document.cookie.substring(j, endstr));
        }
        i = document.cookie.indexOf(" ", i) + 1;
        if(i == 0) break;
    }
    return null;
}
function test(insert) {
    document.cookie = "nickname=" + escape(insert); //寫入Cookie
    document.getElementById("codeboxy").innerHTML = getCookie("nickname"); //輸出Cookie
}
</script>
<a href="javascript:test('程式方盒子');">Click me</a>
<div id="codeboxy"></div>
說明:
自定義getCookie函式,
可掃描cookie內指定之name的中文cookie內容。

2011年7月21日 星期四

getElementsByClassName

標題:自定義getElementsByClassName函式
<script type="text/javascript">
function getElementsByClassName(className, parentElement){
    if (typeof parentElement == 'string'){
        parentElement = document.getElementById(parentElement);
    } else if (typeof parentElement != 'object' || typeof parentElement.tagName != 'string'){
        parentElement = document.body;
    }
    var elems = parentElement.getElementsByTagName("*");
    var result=[];
    for (i=0; j=elems[i]; i++) {
        if ((" "+j.className+" ").indexOf(" "+className+" ")!=-1) {
            result.push(j);
        }
    }
    return result;
}
function test() {
    var divs1 = getElementsByClassName('myclass');
    var divs2 = getElementsByClassName('myclass','parent');
    var divs3 = getElementsByClassName('myclass',document.getElementById('parent'));
    alert(divs1[0].innerText);
    alert(divs2[1].innerText);
    alert(divs3[2].innerText);
}
</script>
<a href="javascript:test();">Click me</a>
<div id="parent">
    <div class="myclass">1</div>
    <div class="myclass">2</div>
    <div class="myclass">3</div>
</div>
說明:
自定義getElementsByClassName函式,
可掃描指定id內之所有class名稱並以陣列儲存。