| 編程(Programming)是編定程序的中文簡(jiǎn)稱,就是讓計(jì)算機(jī)代碼解決某個(gè)問(wèn)題,對(duì)某個(gè)計(jì)算體系規(guī)定一定的運(yùn)算方式,使計(jì)算體系按照該計(jì)算方式運(yùn)行,并最終得到相應(yīng)結(jié)果的過(guò)程。為了使計(jì)算機(jī)能夠理解(understand)人的意圖,人類就必須將需解決的問(wèn)題的思路、方法和手段通過(guò)計(jì)算機(jī)能夠理解的形式告訴計(jì)算機(jī),使得計(jì)算機(jī)能夠根據(jù)人的指令一步一步去工作,完成某種特定的任務(wù)。這種人和計(jì)算體系之間交流的過(guò)程就是編程。 【實(shí)例名稱】 JavaScript 過(guò)濾 SQL 注入字符 【實(shí)例描述】 由于大多數(shù)的數(shù)據(jù)提交語(yǔ)句都是通過(guò)多個(gè)字符串進(jìn)行連接,所以為了防止SQL 的注入字符,本例介紹一種過(guò)濾特殊字符的方法。 【實(shí)例代碼】
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>標(biāo)題頁(yè)</title>
<script LANGUAGE="JavaScript">
function check(inputStr) {
if (typeof(inputStr) != "string") { return inputStr; } //判斷是否是字符串類型
var tmpValue = inputStr;
//以下搜索字符串中的特殊字符,如果存在,則替換成""
while (tmpValue.indexOf(';') > -1) {tmpValue = tmpValue.replace(';',''); }
while (tmpValue.indexOf('<') > -1) {tmpValue = tmpValue.replace('<',''); }
while (tmpValue.indexOf('>') > -1) {tmpValue = tmpValue.replace('>',''); }
while (tmpValue.indexOf('--') > -1) {tmpValue = tmpValue.replace('--',''); }
while (tmpValue.indexOf(",") > -1) {tmpValue = tmpValue.replace(",",""); }
while (tmpValue.indexOf("'") > -1) {tmpValue = tmpValue.replace("'",""); }
while (tmpValue.indexOf("?") > -1) {tmpValue = tmpValue.replace("?",""); }
document.getElementById("txt1").value = tmpValue; //重新顯示更改后的變量
}
</script>
</head>
<body>
<input type=text id="txt1" value="select * from userinfo where username=zhang' and passwrod=2" style="width: 392px">
<input type=button value="提交" onClick="check(txt1.value)">
</body>
</html>
【運(yùn)行效果】 
【難點(diǎn)剖析】 本例的重點(diǎn)是對(duì)特殊字符的判斷。sQL需要防范的注入字符在代碼中被一一列舉,使用“indexOF”方法,可以判斷字符串中是否包含這些字符。如果“indexOf”返回“一1”,則表示不包含指定的特殊字符。
【源碼下載】 本實(shí)例JS代碼下載
使用編程語(yǔ)言寫(xiě)的程序,由于每條指令都對(duì)應(yīng)計(jì)算機(jī)一個(gè)特定的基本動(dòng)作,所以程序占用內(nèi)存少、執(zhí)行效率高。 |