shaoqin 发表于 2015-8-24 10:41:34

Ajax & PHP 边学边练 之二 实例

  本篇通过一个实例介绍Ajax与PHP结合使用的方式,可以下载该实例的源程序以便更好理解。压缩包中functions.js就是Ajax核心代码了,所有的操作效果都是通过它来实现的。下文的代码解释都是提取自functions.js。
  效果1. 当鼠标放在某日上时,如果当天有备忘录,则会显示出来,如下图:


function checkfortasks (thedate, e){
//找到页面中taskbox对应<div>设置为可见
theObject = document.getElementById(&quot;taskbox&quot;);
theObject.style.visibility = &quot;visible&quot;;
//初始化taskbox位置
var posx = 0;
var posy = 0;
//定位taskbox位置为鼠标位置
posx = e.clientX + document.body.scrollLeft;
posy = e.clientY + document.body.scrollTop;
theObject.style.left = posx + &quot;px&quot;;
theObject.style.top = posy + &quot;px&quot;;
//设置PHP请求页面
serverPage = &quot;taskchecker.php?thedate=&quot; + thedate;
//设置PHP返回数据替换位置
objID = &quot;taskbox&quot;;
var obj = document.getElementById(objID);
//发送请求并加载返回数据
xmlhttp.open(&quot;GET&quot;, serverPage);
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
obj.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
}
  
  效果2. 当鼠标点击某日录入姓名时,系统会自动检索姓名是否存在,并可以通过选择填入姓名框中,如图:


function autocomplete (thevalue, e){
//定位页面中autocompletediv(显示检索姓名的标签)的<div>位置
theObject = document.getElementById(&quot;autocompletediv&quot;);
//设置为可见
theObject.style.visibility = &quot;visible&quot;;
theObject.style.width = &quot;152px&quot;;
//设置检索标签位置
var posx = 0;
var posy = 0;
posx = (findPosX (document.getElementById(&quot;yourname&quot;)) + 1);
posy = (findPosY (document.getElementById(&quot;yourname&quot;)) + 23);
theObject.style.left = posx + &quot;px&quot;;
theObject.style.top = posy + &quot;px&quot;;
//设定事件为键盘录入
var theextrachar = e.which;
if (theextrachar == undefined){
theextrachar = e.keyCode;
}
//设定加载检索名单位置
var objID = &quot;autocompletediv&quot;;
//设定PHP请求页面,并将用户输入的姓名传值过去(同时考虑到Backspace作用)
if (theextrachar == 8){
if (thevalue.length == 1){
var serverPage = &quot;autocomp.php&quot;;
}
else{
var serverPage = &quot;autocomp.php&quot; + &quot;?sstring=&quot; + thevalue.substr(0, (thevalue.length -1));
}
}
else{
var serverPage = &quot;autocomp.php&quot; + &quot;?sstring=&quot; + thevalue + String.fromCharCode(theextrachar);
}
//发送请求并加载返回数据
var obj = document.getElementById(objID);
xmlhttp.open(&quot;GET&quot;, serverPage);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
obj.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
}
  源代码下载
页: [1]
查看完整版本: Ajax & PHP 边学边练 之二 实例