还是用的小黄人和模拟表单提交,以避免刷新页面。因为之前已经介绍过注册的方法,这里就直接上代码。需要注意的只有一点,就是我们用了两次定义XMLHttpRequest()对象(就是两套)。注意仔细看哦。
前台代码:

varbtn=document.getElementById("btn");
varmyname=document.getElementById("myname");
vardisp=document.getElementById("disp");
varmypic=document.getElementById("mypic");
//var jsonstr;
myname.onblur=function(){
//console.log(this.value);
varxhr= newXMLHttpRequest();
//数据加载成功后执行
xhr.onload=function(){
if(this.responseText=="fail"){
disp.innerHTML="用户已注册,还是换一个吧";
}else{
disp.innerHTML=""
}
}
varformData= newFormData();
formData.append("myname",this.value);
xhr.open("POST","注册.php",true);
xhr.send(formData);
}
btn.onclick=function(){
varxhr= newXMLHttpRequest();
xhr.onload=function(){
jsonstr=JSON.parse(this.responseText);
console.log(jsonstr);
document.getElementById("mypic").src=jsonstr[0];
}
varformData= newFormData();
formData.append("name",document.getElementById("myname").value);
formData.append("sex",document.getElementById("sex").value);
formData.append("school",document.getElementById("school").value);
formData.append("pic",document.getElementById("pic").files[0]);
xhr.open("POST","注册.php",true);
xhr.send(formData);
}
后台代码:
//验证用户名是否重复
if(!empty($_POST['myname'])) {
$file=fopen("record.txt","r");
$name=$_POST['myname'];
$judge="success";
while(!feof($file)){
$lines=fgets($file);
$arr=array("");
if($lines){
$arr=explode("|",$lines);
}
if($arr[0]==$name){
//echo $arr[0]."|".$name;
$judge="fail";
break;
}
}
echo$judge;
//exit;
}
//完成用户注册
if(!empty($_FILES['pic']['name'])){
//上传头像
$result=move_uploaded_file($_FILES['pic']['tmp_name'],$_FILES['pic']['name']);
if($result){
$arr= array('成功');
if($_POST){
$fp=fopen("record.txt","a+");
$name=htmlspecialchars($_POST['name']);
$sex=htmlspecialchars($_POST['sex']);
$school=htmlspecialchars($_POST['school']);
$pic=$_FILES['pic']['name'];
$line=$name."|".$sex."|".$school."|". $pic."\n";
fwrite($fp,$line);
fclose($fp);
}
echojson_encode(array($pic));
}else{
$arr2= array("error");
echojson_encode($arr2);
}
}
?>