Ajax+PHP 边学边练之四 表单

yipeiwu_com5年前PHP代码库
谈到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值写入数据库。
notask 
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");
?>

源代码下载

相关文章

php实现登陆模块功能示例

本文实例讲述了php实现登陆模块功能的方法。分享给大家供大家参考,具体如下: 最近在学习php。学了一点关于登陆的东西,写下来备忘。 新建四个页面,分别命名为: login.php ch...

php上传文件并显示上传进度的方法

本文实例讲述了php上传文件并显示上传进度的方法。分享给大家供大家参考。具体如下: 记得上传文件的时候要大点,不然还没看出来就上传完了,并且上传的文件不要太大,上G的就算了,2G的我试了...

php将数据库中所有内容生成静态html文档的代码

复制代码 代码如下: <?php /* author:www.5dkx.com done:生成html文档 date:2009-10-27 */ require_once("con...

PHP关于htmlspecialchars、strip_tags、addslashes的解释

PHP的htmlspecialchars、strip_tags、addslashes是网页程序开发中常见的函数,今天就来详细讲述这些函数的用法: 1.函数strip_tags:去掉 HT...

说明的比较细的php 正则学习实例

"^The": 匹配以 "The"开头的字符串;    "of despair$": 匹配以 "of despair...