谈到Form就涉及到一个发送请求方式问题(GET和POST),对于GET和POST的使用和区别在本文就不详细说明了,一般对于Web开发由于POST传值为隐式且传输数据量较大所以比较常用。在本例中对functions.js进行下修改,将创建XMLHttp对象程序创建为一个函数processajax。
<BR>function processajax (serverPage, obj, getOrPost, str){ <BR>//将创建XMLHttpRequest对象写到getxmlhttp()函数中,并获取该对象 <BR>xmlhttp = getxmlhttp (); <BR>//GET方式(和前面几篇一样) <BR>if (getOrPost == "get"){ <BR>xmlhttp.open("GET", serverPage); <BR>xmlhttp.onreadystatechange = function(){ <BR>if (xmlhttp.readyState == 4 && xmlhttp.status == 200){ <BR>obj.innerHTML = xmlhttp.responseText; <BR>} <BR>} <BR>xmlhttp.send(null); <BR>} <BR>//POST方式 <BR>else{ <BR>//第三个true参数将打开异步功能 <BR>xmlhttp.open("POST", serverPage, true); <BR>//创建POST请求 <BR>xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=GB2312"); <BR>xmlhttp.onreadystatechange = function() { <BR>if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { <BR>obj.innerHTML = xmlhttp.responseText; <BR>} <BR>} <BR>//表单(Form)传值 <BR>xmlhttp.send(str); <BR>} <BR>} <BR>
在下图中当点击“Submit”按钮后会激发submitform函数(functions.js),在该函数中会通过getformvalues函数检查Form内容是否都填写完毕,否则提示哪项未填写。当检查通过后会调用process_task.php程序,它会将Form值写入数据库。
submitform 函数:
<BR>function submitform (theform, serverPage, objID, valfunc){ <BR>var file = serverPage; <BR>//检查Form值 <BR>var str = getformvalues(theform,valfunc); <BR>//Form全部填写 <BR>if (aok == true){ <BR>obj = document.getElementById(objID); <BR>//运行Ajax进行传值 <BR>processajax(serverPage, obj, "post", str); <BR>} <BR>} <BR>
getformvalues 函数:
<BR>function getformvalues (fobj, valfunc){ <BR>var str = ""; <BR>aok = true; <BR>var val; <BR>//遍历Form中所有对象 <BR>for(var i = 0; i < fobj.elements.length; i++){ <BR>if(valfunc){ <BR>if (aok == true){ <BR>val = valfunc (fobj.elements[i].value,fobj.elements[i].name); <BR>if (val == false){ <BR>aok = false; <BR>} <BR>} <BR>} <BR>str += fobj.elements[i].name + "=" + escape(fobj.elements[i].value) + "&"; <BR>} <BR>//将Form值以String形式返回 <BR>return str; <BR>} <BR>
process_task.php 程序:
<BR><?php <BR>require_once ("dbconnector.php"); <BR>opendatabase(); <BR>//对数据预处理 <BR>$yourname = strip_tags (mysql_real_escape_string ($_POST['yourname'])); <BR>$yourtask = strip_tags (mysql_real_escape_string ($_POST['yourtask'])); <BR>$thedate = strip_<b>%本文@来源gao@!dai!ma.com搞$$代^@码!网</b><strong>搞代gaodaima码</strong>tags (mysql_real_escape_string ($_POST['thedate'])); <BR>//创建Insert语句 <BR>$myquery = "INSERT INTO task (name, thedate, description) VALUES ('$yourname','$thedate','$yourtask')"; <BR>//执行SQL语句 <BR>if (!mysql_query ($myquery)){ <BR>header ("Location: theform.php?message=There was a problem with the entry."); <BR>exit; <BR>} <BR>//返回成功信息 <BR>header ("Location: theform.php?message=Success"); <BR>?> <BR>
源代码下载