編程(Programming)是編定程序的中文簡稱,就是讓計算機代碼解決某個問題,對某個計算體系規定一定的運算方式,使計算體系按照該計算方式運行,并最終得到相應結果的過程。為了使計算機能夠理解(understand)人的意圖,人類就必須將需解決的問題的思路、方法和手段通過計算機能夠理解的形式告訴計算機,使得計算機能夠根據人的指令一步一步去工作,完成某種特定的任務。這種人和計算體系之間交流的過程就是編程。 【實例名稱】 讀寫Cookie的函數JS代碼怎么寫 【實例描述】 cookie是客戶端用來保存數據的對象,本例將所有有關Cookie的操作封裝成一個函數庫。讀者通過學習本例可以全面地掌握Cookie的使用。 【實例代碼】 <html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>標題頁-本站(www.xue51.com)</title>
<script Language="JavaScript">
//獲得Cookie解碼后的值
function GetCookieVal(offset)
{
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1)
endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}
//設定Cookie值-將值保存在Cookie中
function SetCookie(name, value)
{
var expdate = new Date();
//獲取當前日期
var argv = SetCookie.arguments;
//獲取cookie的參數
var argc = SetCookie.arguments.length;
//cookie的長度
var expires = (argc > 2) ? argv[2] : null;
//cookie有效期
var path = (argc > 3) ? argv[3] : null;
//cookie路徑
var domain = (argc > 4) ? argv[4] : null;
//cookie所在的應用程序域
var secure = (argc > 5) ? argv[5] : false;
//cookie的加密安全設置
if(expires!=null) expdate.setTime(expdate.getTime()
+ ( expires * 1000 ));
document.cookie = name + "=" + escape (value)
+((expires == null) ? "" : ("; expires="+ expdate.toGMTString()))
+((path == null) ? "" : ("; path=" + path)) +
((domain == null) ? "" : ("; domain=" + domain))
+((secure == true) ? "; secure" : "");
}
//刪除指定的Cookie
function DelCookie(name)
{
var exp = new Date();
exp.setTime (exp.getTime() - 1);
var cval = GetCookie (name);
//獲取當前cookie的值
document.cookie = name + "=" + cval + "; expires="+ exp.toGMTString();
//將日期設置為過期時間
}
//獲得Cookie的值-name用來搜索Cookie的名字
function GetCookie(name)
{
var arg = name + "=";
var argLen= arg.length;
//指定Cookie名的長度
var cookieLen= document.cookie.length;
//獲取cookie的長度
var i = 0;
while (i < cookieLen)
{
var j = i + argLen;
if (document.cookie.substring(i, j) == arg)
//依次查找對應cookie名的值
return GetCookieVal (j);
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
</script>
</head>
<body>
<input type=text name="txt1" value="搜索引擎是百度">
<input type=button value="保存Cookie"
onClick="javascript:SetCookie('sousuo', txt1.value)">
<input type=button value="獲取Cookie"
onClick=" javascript:alert(GetCookie('sousuo'))">
</body>
</html>
【運行效果】
 【難點剖析】 本例的重點是“document.cookie”,在JavaScript中不管是保存Cookie還是獲取Cookie,都是使用“document.cookie”。具體的使用方法參考代碼中的注釋。 【源碼下載】 為了JS代碼的準確性,請點擊:讀寫Cookie的函數 進行本實例源碼下載
使用編程語言寫的程序,由于每條指令都對應計算機一個特定的基本動作,所以程序占用內存少、執行效率高。 |