ajax+FormData+javascript 实现无刷新上传附件

<!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=""/>';}
} }
xhr.open("POST","/1.php");
//使用formData不用设置表头
//xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send(fmdata);
return false;
} }
</script>
</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>
文件<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); ?>
上一篇:Http协议之Request和Response


下一篇:linux 后台运行nohup & ctrl+z