<!doctype html> <html> <head> <meta charset="utf-8"> <title>无标题文档</title> <script type="text/javascript"> window.onload=function() { var fm=document.getElementsByTagName("form")[0]; fm.onsubmit=function() { //var username=document.getElementById("username").value; // var password=document.getElementById("password").value; // var email=document.getElementById("email").value; //var fmdata="username="+username+"&password="+password+"&email="+email; var fmdata=new FormData(fm); var xhr=new XMLHttpRequest(); xhr.onreadystatechange=function() { if(xhr.readyState==4) { eval("var obj="+xhr.responseText); document.getElementById("scjg").innerHTML=obj.jg; if(obj.name!=null){ document.getElementById("sctp").innerHTML='<img src=\"'+obj.name+'\" width="89" height="70" alt=""/>';} } } //设置监听事件ajax.upload.onprogress xhr.upload.onprogress=function(evt){ //感知附件上传情况,利用事件感知 //console.log(evt); var loaded=evt.loaded; var total=evt.total; var per=Math.floor((loaded/total)*100)+"%"; document.getElementById("jdn").style.width=per; document.getElementById("jdn").innerHTML=per; } xhr.open("POST","/1.php"); //使用formData不用设置表头 //xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xhr.send(fmdata); return false; } } </script> <style> #jdw{ margin:10px; height:20px; border:solid 1px #666; width:200px;} #jdn{height:20px; background-color:#F00; width:0px; } </style> </head> <body> <div id="scjg"></div> <div id="sctp"></div> ajax+FormData+javascript 实现无刷新表单注册 <form method="post"> 姓名<input name="username" type="text" id="username"> <br> 密码<input name="password" type="password" id="password"> <br> 邮箱<input name="email" type="text" id="email"> <br> <div id="jdw"><div id="jdn"></div></div> 文件<input name="nfile" type="file" id="nfile"> <br> <input type="submit" value="提交"></form> </body> </html>
<?php //print_r($_POST); //print_r($_FILES); $ary=array(); if($_FILES["nfile"]["error"]>0){ $ary['jg']='上传附件有问题,有可能没有附件'; echo json_encode($ary); exit(); } $path="./upfile/"; $name=$_FILES["nfile"]['name']; //附件上传 if(move_uploaded_file($_FILES["nfile"]['tmp_name'],iconv("UTF-8","GBK",$path.$name))) { $ary['jg']="上传成功"; $ary['name']=$path.$name; }else{ $ary['jg']="上传失败"; } echo json_encode($ary); ?>