進階技術(一)

XML

XML(Extendable Markup Language)最主要的功能是用來「資料傳遞」用,例如A網站可將要分享出來的資料(如最新訊息或產品資訊…等), 轉成XML格式讓B網站可以直接讀取及引用,因此使用者可自行定義標籤(tags)名稱及結構,以利引用者辦識結構及資料內容。

XML 範例

<article>

   <title>Simple XML</title>

   <date>September 19, 2001</date>

   <author>
      <firstName>Tem</firstName>
      <lastName>Nieto</lastName>
   </author>

   <summary>XML is pretty easy.</summary>

   <content>Once you have mastered XHTML, XML is easily
      learned. You must remember that XML is not for
      displaying information but for managing information.
   </content>

</article>

XML 運作規則

資料型式特殊的XML

XML Parser

The XML DOM (Document Object Model) defines the properties and methods for accessing and editing XML. However, before an XML document can be accessed, it must be loaded into an XML DOM object. All modern browsers have a built-in XML parser that can convert text into an XML DOM object.

Parsing a Text String

This example parses a text string into an XML DOM object, and extracts the info from it with JavaScript:

例題

<html>
<body>

<p id="demo"></p>

<script>
var text, parser, xmlDoc;

text = "<bookstore><book>" +
"<title>Everyday Italian</title>" +
"<author>Giada De Laurentiis</author>" +
"<year>2005</year>" +
"</book></bookstore>";

parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");

document.getElementById("demo").innerHTML =
xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
</script>

</body>
</html>
例:parser.htm
  1. article.xml
  2. xml and dtd(Document Type Definition)
  3. DOMExample.html
  4. games.xml
  5. xml and xsl(Extensible Stylesheet Language) for games
  6. sorting.xml
  7. xml and xsl for sorting

參考資料

  1. XML Tutorial
  2. Development Exchange XML Zone
  3. XMLINFO
  4. Project Cool Developer Zone site
  5. http://www.zvon.org/

XHTML

XHTML(Extendable HTML)

XHTML 規則

所有標籤必須有結尾
    <br />
    <img src="fn.gif" />
元件有大小寫之分
<script language="JavaScript">
    var x=1;
</script>
屬性值都要用引號標示
    <img src="fn.gif" width="100" height="100" />
    <input type="text" name="yourname" size="25" />
    <input type="checkbox" name="cb1" value="yes" checked="checked" />
元件的多層排列必須適當
name 屬性用 id 屬性替換
    <form name="f1" id="f1">
    <input type="text" name="yourname" id="yourname" size="25" />
    </form>

參考資料

  1. XHTML 1.0 Recommendation
  2. W3C XHTML validation service site

正規運算式

正規表達式是被用來匹配字串中字元組合的模式。 JavaScript 的正規式(Regular expressions)是一個內建的物件。

建立正規運算式

    var patt=new RegExp(pattern, modifiers);

或更簡潔的方法

    var patt=/pattern/modifiers;
例如:
    var tomatch=/our/;

正規運算式的測試

    var tomatch=/our/;
    tomatch.test("pour");
<script language="JavaScript">
<!--
    var thename=window.prompt("Enter your name", "");
    var tomatch=/John/;
    if ( tomatch.test(thename) )
        window.alert("Wow, we have the same name!");
    else
        window.alert("Not my name, but it will work!");
//-->
</script>

旗標(flag)

pattern 代表以正規表示法來顯示的字串,flag 則是比對的方式。flag 的值有三種: 例如:
<script language="JavaScript">
<!--
    var thename=window.prompt("Enter your name", "");
    var tomatch=/John/i;
    if ( tomatch.test(thename) )
        window.alert("Wow, we have the same name!");
    else
        window.alert("Not my name, but it will work!");
    //-->
</script>

看效果

使用字串方法

正規式經常使用這兩個字串方法: search() and replace()。

replace() 方法

<p>Replace "Microsoft" with "W3Schools" in the paragraph below:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo">Please visit Microsoft!</p>

<script>
function myFunction() {
  let text = document.getElementById("demo").innerHTML;
  document.getElementById("demo").innerHTML =
  text.replace(/microsoft/i, "W3Schools");
}
</script>

看效果

search() 方法

search() 方法執行搜索正則表達式和此 String 物件之間的匹配項。 回值是第一個匹配項的索引,如果未找到匹配項,則為 -1。
<script language="JavaScript">
<!--
var paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';

// any character that is not a word character or whitespace
var regex = /[^\w\s]/g;

document.write("The pattern is found at "  + paragraph.search(regex));
// expected output: 43

document.write("<p>The pattern found is " + paragraph[paragraph.search(regex)]);
// expected output: "."
//-->
</script>

看效果

exec()

exec() 方法檢索字串中的指定值。 返回值是比對到的值,以陣列表示。 如果沒有發現匹配,則返回null。
正規式:  /d(b+)(d)/i
<br>// 比對一個字元 d,後面接著一或多個 b,再接著一個 d
<br>// Remember matched b's and the following d
<br>// 忽略大小寫
<p>input: </p>
<p id="demo"></p>
<p>output: </p>
<p id="demo2"></p>

<script>
var myRe = /d(b+)(d)/i;
var myArray = myRe.exec('cdbBdbsbz');
let text = myArray.toString();
document.getElementById("demo").innerHTML = myArray.input;
document.getElementById("demo2").innerHTML = text;
</script>

看效果

正規式模式

括號用於查找一系列字元:
正規式 說明
[abc] 符合所包含的任意一個字元。例如,「[abc]」可以符合「plain」中的「a」。
[0-9] 找到括號之間的任何數字。連字元 - 如果出現在字串中間表示字元範圍描述
x|y 沒有包圍在()里,其範圍是整個正規表示式。例如,「z|food」能符合「z」或「food」。「(?:z|f)ood」則符合「zood」或「food」。

元字元(metacharacter)是具有特殊含義的字元:
元字 說明
^ 符合輸入字串的開始位置。
\d 符合一個數字字元。等價於[0-9]。注意Unicode正規表示式會符合全形數字字元。
\D 符合一個非數字字元。等價於[^0-9]。
\s 查找空白字符
\b 符合一個單詞邊界,也就是指單詞和空格間的位置。例如,「er\b」可以符合「never」中的「er」,但不能符合「verb」中的「er」。
\w 符合包括底線的任何單詞字元。等價於「[A-Za-z0-9_]」。注意Unicode正規表示式會符合中文字元。
\uxxxx Unicode 跳脫字元序列。其中xxxx是一個用四個十六進位數字表示的Unicode字元。例如,\u00A9符合著作權符號(c)。

量詞(Quantifier)定義數量:
量詞 說明
+ 符合前面的子表達式一次或多次。例如,「zo+」能符合「zo」以及「zoo」,但不能符合「z」。
* 符合前面的子表達式零次或多次。例如,zo*能符合「z」、「zo」以及「zoo」。
? 符合前面的子表達式零次或多次。例如,「do(es)?」可以符合「does」中的「do」和「does」。
{n} n是一個非負整數。符合確定的n次。例如,「o{2}」不能符合「Bob」中的「o」,但是能符合「food」中的兩個o。
{n,} n是一個非負整數。至少符合n次。例如,「o{2,}」不能符合「Bob」中的「o」,但能符合「foooood」中的所有o。「o{1,}」等價於「o+」。「o{0,}」則等價於「o*」。
{n,m} m和n均為非負整數,其中n<=m。最少符合n次且最多符合m次。例如,「o{1,3}」將符合「fooooood」中的前三個o。「o{0,1}」等價於「o?」。請注意在逗號和兩個數之間不能有空格。

更多量詞,請參考PCRE表達式全集

建立有威力的形式

電話號碼驗證

使用的模式:/(?:\d{3}|\(\d{3}\))([-\/\.])\d{3}\1\d{4}/

說明如下:

  1. 三個數字 \d{3} 或左右括弧括住三個數字\(\d{3}\) ,都在非捕獲組(?:)內。即匹配到,不被記住。
  2. 接著一個破折號-,正斜杠/ 或小數點。([-\/\.])
  3. 接著三個數字 \d{3}
  4. 接著 在(第一個)捕獲組中記住的匹配\1,跳過非捕獲組(?:)的匹配。
  5. 接著三個數字 \d{4}
<html>
<head>
<meta http-equiv=Content-Type content="text/html; charset=big5">
<script language="JavaScript">
<!--
function check_it()
{
    var tomatch= /(?:\d{3}|\(\d{3}\))([-\/\.])\d{3}\1\d{4}/;
    var phonenum=document.f1.t1.value;
    if ( tomatch.test(phonenum) )
        document.getElementById("demo").innerHTML="<font color='red'><b>電話號碼正確!</b></font>";
    else
        document.getElementById("demo").innerHTML= "<font color='red'><b>請輸入正確的電話號碼!</b></font>";
}
//-->
</script>
</head>
<body>
<h3>電話號碼驗證</h3>
<p>
  請輸入電話號碼 (含區域碼) ,如: ###-###-####
<form name="f1" id="f1">
<p>
Enter your phone number:<br />
<input type="text" name="t1" id="t1" value = "(408)-978-2345"/>
<input type="button" name="go" value="Go!" onClick="check_it()"> </form> <p id="demo"></p> </body>

看效果

電子郵件位址驗證

使用的模式:/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z]+$/

說明如下:

// ^\w+:@ 之前必須以一個以上的文字&數字開頭,例如 abc
// ((-\w+):@ 之前可以出現 1 個以上的文字、數字或「-」的組合,例如 -abc-
// (\.\w+)):@ 之前可以出現 1 個以上的文字、數字或「.」的組合,例如 .abc.
// ((-\w+)|(\.\w+))*:以上兩個規則以 or 的關係出現,並且出現 0 次以上 (所以不能 –. 同時出現)
// @:中間一定要出現一個 @
// [A-Za-z0-9]+:@ 之後出現 1 個以上的大小寫英文及數字的組合
// (\.|-):@ 之後只能出現「.」或是「-」,但這兩個字元不能連續時出現
// ((\.|-)[A-Za-z0-9]+)*:@ 之後出現 0 個以上的「.」或是「-」配上大小寫英文及數字的組合
// \.[A-Za-z]+$/:@ 之後出現 1 個以上的「.」配上大小寫英文及數字的組合,結尾需為大小寫英文
<html>
<head>
<script language="JavaScript">
<!--
function check_it()
{
    var tomatch=/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z]+$/;
    var emadd=document.f1.t1.value;
    if ( tomatch.test(emadd) )
        document.getElementById("demo").innerHTML="Email 位址正確!";
    else
        document.getElementById("demo").innerHTML="請輸入正確的 Email 位址!";
    }
}
//-->
</script>
</head>
<body>
<h3>電子郵件位址驗證</h3>
<form name="f1" id="f1" >
Your name:
<input type="text" name="yourname" size="25">
<p>
Enter your E-mail address:<br />
<input type="text" name="t1" id="t1" /><br />
<input type="button" name="go" value="Go!" onClick="check_it()">
</form>

<p id="demo"></p>
</body>

看效果

參考:

  1. 正規表達式
  2. 規則運算式語言 - 快速參考
  3. 正規表示法
  4. regex101: build, test, and debug regex
  5. JavaScript 表單驗證

Cookie

Cookies 是一些數據, 存儲於你電腦上的文本文件中。

當web 服務器向瀏覽器發送web 頁面時,在連接關閉後,服務端不會記錄用戶的信息。

Cookies 的作用就是用於解決"如何記錄客戶端的用戶信息":

Cookies 以名/值對形式存儲,如下所示:
             username=John Doe

當瀏覽器從服務器上請求web 頁面時, 屬於該頁面的cookies 會被添加到該請求中。 服務端通過這種方式來獲取用戶的信息。

設定Cookie

    document.cookie="name=tasty1";
    document.cookie="name:tasty1";
    document.cookie="name=tasty1&fav=Sugar";
    document.cookie="name:tasty1|fav:Sugar";

escape()方法

    document.cookie="name=tasty1&fav=Chocolate Chip";

    document.cookie=escape("name=tasty1&fav=Chocolate Chip");

允許使用者輸入

    function set_it()
    {
        var thefav=window.prompt("Enter your favorite type of cookie", "");
        var thetext="name=tasty1&fav=" + thefav;
        var newtext=escape(thetext);
        document.cookie=newtext;
    }

設定期滿資料

    function set_it()
    {
        var thetext="quote=I have a quote&";
        var toexpire=new Date("June 15, 2003");
        var expdate="expire="+toGMTstring(toexpire);
        thetext+=expdate;
        var newtext=escape(thetext);
        document.cookie=newtext;
    }

讀Cookie

分成 name/value 對
    function read_it()
    {
        var mycookie=document.cookie;
        var fixed_cookie=unescape(mycookie);
        var thepairs=fixed_cookie.split(&);
    }

再將每對 name/value 分成 name 和 value:

    function read_it()
    {
        var mycookie=document.cookie;
        var fixed_cookie=unescape(mycookie);
        var thepairs=fixed_cookie.split("&");
        var pair1=thepairs[0];
        var pair2=thepairs[1];
        var namevalue1=pair1.split("=");
        var namevalue2=pair2.split("=");
    }

呈現出來:

function read_it()
    {
        var mycookie=document.cookie;
        var fixed_cookie=unescape(mycookie);
        var thepairs=fixed_cookie.split("&");
        var pair1=thepairs[0];
        var pair2=thepairs[1];
        var namevalue1=pair1.split("=");
        var namevalue2=pair2.split("=");
        window.alert("The cookie's " + namevalue1[0] + " is" + namevalue1[1]);
        window.alert("The cookie's " + namevalue2[0] + " is" + namevalue2[1]);
    }

確定Cookie是否存在:

    function read_it()
    {
        if (document.cookie)
        {
            var mycookie=document.cookie;
            var fixed_cookie=unescape(mycookie);
            var thepairs=fixed_cookie.split("&");
            var pair1=thepairs[0];
            var pair2=thepairs[1];
            var namevalue1=pair1.split("=");
            var namevalue2=pair2.split("=");
            window.alert("The cookie's " + namevalue1[0] + " is" + namevalue1[1]);
            window.alert("The cookie's " + namevalue2[0] + " is" + namevalue2[1]);
        }
        else
        {
            set_it();
        }
    }
例:pr16_2.html 例:cookies.html