复制代码 代码如下:
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 程序:
复制代码 代码如下:
<?php
require_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");
?>
源代码下载
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!