发这篇博客的时候我是自己在研究这个XMLHttpRequest请求,在别人的博客上面知道XMLHttpRequest新加了一个FormData的东西,好像现在APP请求后台也有用这种方式的吧。
别的不多说,我一直在纠结js怎样获取到form表单中file类型的值,或者说是数据。一直没有找到方法,前两天看了一个博客,他是通过Form表单来初始化FormData,得到 一个对象然后通过Ajax方式将文件数据发送到PHP文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>测试FormData方式上传文件</title> <style> body{margin: 0;padding: 50px 0 0 0;} .topDiv{margin-left: 40%; margin-top: 200px; float: left; position: absolute;} .topDiv ul li{list-style: none; margin-top: 10px;} .topDiv ul li label{color: #999;} .topDiv ul li input{width: 150px;} </style> </head> <body> <div class="topDiv" align="center"> <form> <ul> <li> <label>图片名称:</label> <input type="text" name="name" id="name" value=""> </li> <li> <label>图片上传:</label> <img src="http://usr.im/100x50" width="150" height="100"> </li> <li> <input type="button" onclick="onFormPost()" value="提交"> </li> </ul> </form> <form id="formData" style="display: none"> <ul> <li> <label>选择图片:</label> <input type="file" name="file" onchange="onFormPost()" value=""> </li> </ul> </form> </div> </body> <script type="text/javascript" src="../Public/js/jquery-2.1.4.min.js?ver=1"></script> <script> function onFormPost(){ var myForm=new FormData(document.getElementById('formData')); // myForm.append("name",document.getElementById('name').value); // myForm.append("file",document.getElementsByName("file").files[0]) // var myXhr=new XMLHttpRequest(); // myXhr.open("post","upload.php"); // myXhr.send(myForm); $.ajax({ url: "upload.php", type: "POST", data: myForm, processData: false, // 告诉jQuery不要去处理发送的数据 contentType: false, // 告诉jQuery不要去设置Content-Type请求头 success:function(data){ alert(data); },error:function(){ } }); } </script> </html>
然后只需要在upload.php文件处理上传