通過上一篇文章已經瞭解到如何利用Ajax和PHP對資料庫進行資料讀取,這樣可以動態擷取到資料庫的最新資料。本篇則繼續介紹通過表單(Form)向資料庫中寫入資料。
談到Form就涉及到一個發送請求方式問題(GET和POST),對於GET和POST的使用和區別在本文就不詳細說明了,一般對於Web開發由於POST傳值為隱式且傳輸資料量較大所以比較常用。在本例中對functions.js進行下修改,將建立XMLHttp對象程式建立為一個函數processajax。
function processajax (serverPage, obj, getOrPost, str){ //將建立XMLHttpRequest對象寫到getxmlhttp()函數中,並擷取該對象 xmlhttp = getxmlhttp (); //GET方式(和前面幾篇一樣) if (getOrPost == "get"){ xmlhttp.open("GET", serverPage); xmlhttp.onreadystatechange = function(){ if (xmlhttp.readyState == 4 && xmlhttp.status == 200){ obj.innerHTML = xmlhttp.responseText; } } xmlhttp.send(null); } //POST方式 else{ //第三個true參數將開啟非同步功能 xmlhttp.open("POST", serverPage, true); //建立POST請求 xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=GB2312"); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { obj.innerHTML = xmlhttp.responseText; } } //表單(Form)傳值 xmlhttp.send(str); }}
在中當點擊“Submit”按鈕後會激發submitform函數(functions.js),在該函數中會通過getformvalues函數檢查Form內容是否都填寫完畢,否則提示哪項未填寫。當檢查通過後會調用process_task.php程式,它會將Form值寫入資料庫。
submitform 函數:
function submitform (theform, serverPage, objID, valfunc){ var file = serverPage; //檢查Form值 var str = getformvalues(theform,valfunc); //Form全部填寫 if (aok == true){ obj = document.getElementById(objID); //運行Ajax進行傳值 processajax(serverPage, obj, "post", str); }}
getformvalues 函數:
function getformvalues (fobj, valfunc){ var str = ""; aok = true; var val; //遍曆Form中所有對象 for(var i = 0; i < fobj.elements.length; i++){ if(valfunc){ if (aok == true){ val = valfunc (fobj.elements[i].value,fobj.elements[i].name); if (val == false){ aok = false; } } } str += fobj.elements[i].name + "=" + escape(fobj.elements[i].value) + "&"; } //將Form值以String形式返回 return str;}
process_task.php 程式:
<?phprequire_once ("dbconnector.php");opendatabase();//對資料預先處理$yourname = strip_tags (mysql_real_escape_string ($_POST['yourname']));$yourtask = strip_tags (mysql_real_escape_string ($_POST['yourtask']));$thedate = strip_tags (mysql_real_escape_string ($_POST['thedate']));//建立Insert語句$myquery = "INSERT INTO task (name, thedate, description)
VALUES ('$yourname','$thedate','$yourtask')";//執行SQL語句if (!mysql_query ($myquery)){ header ("Location: theform.php?message=There was a problem with the entry."); exit;}//返回成功資訊header ("Location: theform.php?message=Success");?>
原始碼下載