Javascript
1995年,網景公司的布蘭登·艾克正為Netscape Navigator 2.0瀏覽器開發的叫LiveScript的程式語言,後來網景公司與昇陽電腦公司組成的開發聯盟為了讓這門語言搭上java這個程式語言「熱詞」,將其臨時改名為「JavaScript」,日後這成為大眾對這門語言有諸多誤解的原因之一。也就是說,雖然JavaScript和Java二者程式語言部份語法很像,但不是相同的程式語言。有很多語法是不同的。 JavaScript由ECMA訂出標準化的JavaScript稱為ECMAScript。它被世界上的絕大多數網站所使用,也被世界主流瀏覽器(Chrome、IE、FireFox、Safari、Opera)支援。JavaScript是一門基於原型、函式先行的語言,是一門多範式的語言,它支援物件導向編程,指令式編程,以及函數語言程式設計。
Hello World
<!DOCTYPE HTML>
<html>
<head>
<title>簡單的JavaScript Hello World</title>
<script type="text/javascript">
document.write("Hello, world!"); // 於瀏覽器視窗內直接顯示
alert("Hello, world!"); // 開啟對話視窗顯示
console.log("Hello, world!"); // zh-tw:於console裡顯示,需要先開啟開發工具控制台
</script>
</head>
<body>
HTML內容……
</body>
</html>
DOM
文件物件模型(Document Object Model),是W3C組織推薦的處理可延伸標示語言的標準程式介面。
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
Event
<!DOCTYPE html>
<html>
<body>
<p>This example uses the addEventListener() method to execute a function when a user clicks on a button.</p>
<button id="myBtn">Try it</button>
<script>
document.getElementById("myBtn").addEventListener("click", myFunction);
function myFunction() {
alert ("Hello World!");
}
</script>
</body>
</html>
DOM nodes
<!DOCTYPE html>
<html>
<body>
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
</script>
</body>
</html>
jQuery
jQuery是一套跨瀏覽器的最常見的JavaScript函式庫之一,用來簡化HTML與JavaScript之間的操作。
<script>
//Typical start-point
$(function () {
$('img').on('click', function () {
// handle the click event on any img element in the page
});
});
//Chaining
$('div.test')
.add('p.quote')
.addClass('blue')
.slideDown('slow');
//Ajax
$.ajax({
type: 'POST',
url: '/process/submit.php',
data: {
name : 'John',
location : 'Boston',
},
}).done(function(msg) {
alert('Data Saved: ' + msg);
}).fail(function(xmlHttpRequest, statusText, errorThrown) {
alert(
'Your form submission failed.\n\n'
+ 'XML Http Request: ' + JSON.stringify(xmlHttpRequest)
+ ',\nStatus Text: ' + statusText
+ ',\nError Thrown: ' + errorThrown);
});
</script>
jQuery selectors
https://www.w3schools.com/jquery/jquery_ref_selectors.asp
<script>
//class selector
$(".intro")
//id selector
$("#lastname")
//element selector
$("p")
//items
$("p:first")
$("p:last")
$("tr:even")
$("tr:odd")
$("p:first-child")
$("p:nth-child(2)")
$("p:nth-last-child(2)")
//All input elements
$(":input")
$(":button")
$(":selected")\$(":checked")
</script>
Ajax
AJAX是「Asynchronous JavaScript and XML」縮寫,由Jesse James Garrett(傑西·詹姆士·賈瑞特)所提出。
https://en.wikipedia.org/wiki/Ajax_(programming)
// This is the client-side script.
// Initialize the HTTP request.
var xhr = new XMLHttpRequest();
xhr.open('GET', 'send-ajax-data.php');
// Track the state changes of the request.
xhr.onreadystatechange = function () {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
console.log(xhr.responseText); // 'This is the output.'
} else {
console.log('Error: ' + xhr.status); // An error occurred during the request.
}
}
};
// Send the request to send-ajax-data.php
xhr.send(null);
<?php
//send-ajax-data.php
// This is the server-side script.
// Set the content type.
header('Content-Type: text/plain');
// Send the data back.
echo "This is the output.";
?>
XMLHttpRequest 屬性
https://developer.mozilla.org/zh-TW/docs/Web/API/XMLHttpRequest
- XMLHttpRequest.onreadystatechange 一個 EventHandler(事件處理器)函式,會於 readyState 屬性之狀態改變時被呼叫。
- XMLHttpRequest.readyState Read only 回傳一個無符號短整數(unsigned short)代表請求之狀態。
- XMLHttpRequest.response Read only 回傳一個值,可以是 ArrayBuffer、Blob、Document、JavaScript 物件或是 DOMString。根據XMLHttpRequest.responseType 之值決定為何種類型的資料,資料為回應實體中的內容(response entity body)。
- XMLHttpRequest.responseText Read only 回傳一個 DOMString,其內容為請求之回應的文字內容。如請求失敗或尚未發送,則為 null。
- XMLHttpRequest.responseType 為一可列舉(enumerated)值,定義回應內容的資料類型(response type)。 XMLHttpRequest.responseURL Read only 回傳一個回應(response)的序列化 URL,如 URL 為 null 則回傳空字串。
XMLHttpRequest 方法
- XMLHttpRequest.abort() 中止已發出的請求。
- XMLHttpRequest.getAllResponseHeaders() 回傳所有的回應標頭(response headers),為一以斷行字元(CRLF)分行的字串,如未接收到回應則為 null。
- XMLHttpRequest.getResponseHeader() 回傳指定標頭文字之字串,假如回應尚未被接收或是標頭不存在於回應中則為 null。
- XMLHttpRequest.open() 初始化一個請求。此方法用於 JavaScript 中;若要在 native code 中初始化請求,請以 openRequest() 作為替代。
- XMLHttpRequest.overrideMimeType() 覆寫伺服器回傳的 MIME type。
- XMLHttpRequest.send() 發送請求。如果為非同步請求(預設值),此方法將在發出請求後便立即回傳(return)。
- XMLHttpRequest.setRequestHeader() 設定 HTTP 請求標頭(request header)值。setRequestHeader() 可被呼叫的時間點必須於 open() 之後、在 send() 之前。
Example-Ajax Client side
var rr = document.querySelectorAll('input[type="radio"]');
for (var i = 0; i < rr.length; i++)
{
rr[i].addEventListener("change", handler, false);
}
function handler(event) {
//alert('update_vote.php?VID='+this.id+'&VScore='+this.value);
var oReq = new XMLHttpRequest();
oReq.open('GET', 'update_vote.php?VID='+this.id+'&VScore='+this.value);
/*oReq.onreadystatechange = function (aEvt) {
if (oReq.readyState == 4) {
if(oReq.status == 200)
alert(oReq.responseText);
else
alert("Error loading page\n");
}
};*/
//oReq.addEventListener("load", reqListener);
oReq.send();
/*xhr = new XMLHttpRequest();
xhr.open('POST', 'update_test.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (xhr.status === 200 ) {
alert( xhr.readyState+'='+ xhr.responseText);
}
else if (xhr.status !== 200) {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send(encodeURI('SData=' + this.id));*/
}
function reqListener () {
console.log(this.readyState);
alert(this.readyState);
}
Example-Ajax Server side
<?php
//將表單元件的值轉成php變數
if (isset($_REQUEST["VID"]))
{
$vID=htmlspecialchars($_REQUEST["VID"]);
$vScore=htmlspecialchars($_REQUEST["VScore"]);
/*require_once 'testlog.php';
$log = new Logging();
$log->lfile('testlog-sql20171110.txt');
$log->lwrite($vID); $log->lwrite($vScore);
$log->lclose();*/
$dbconfig = array (
'database' => 'web2017',
'username' => 'madoo',
'password' => '4aJu6Cwh4cPKQUuW',
'host' => 'localhost',
'port' => '',
'driver' => 'mysql',
);
$dbconfig = $GLOBALS['dbconfig'];
$dsn = $dbconfig['driver'].":host=".$dbconfig['host'].";dbname=".$dbconfig['database'];
$pdo = new PDO($dsn, $dbconfig['username'],$dbconfig['password']);
$pdo->query("set names utf8");
$sql="UPDATE `vote_record` SET `VScore`=:VScore WHERE `VID`=:VID";
$pdoStatement = $pdo->prepare($sql);
$pdoStatement->bindValue(':VID', $vID, PDO::PARAM_STR);
$pdoStatement->bindValue(':VScore', $vScore, PDO::PARAM_STR);
if (!$pdoStatement->execute()) {
print_r($pdoStatement->errorInfo());
}
}
?>