Ajax+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值写入数据库。
源代码下载谈到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值写入数据库。
源代码下载
« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3