码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-05-05 22:31:38      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:

<!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"  />;}
            }
               
        } 
        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);


?>

 

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

标签:

原文地址:http://www.cnblogs.com/zywf/p/5463429.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!