一、formData向后台传数据<br>
1.formData有set、get、append等方法<br> 1)set():设置数据<br> var formData=new FormData();<br> formData.set('a',2);<br>如果有两个set()方法,且key相同,比如:
formData.set('a',2); formData.set('a',3); 则返回的是32)append():添加数据
var formData=new FormData(); formData.set('a',2);如果有两个set()方法,且key相同,比如:
formData.set('a',2); formData.append('a',3); 则返回的是[2,3] 3)get():得到数据比如通过ajax向后台传数据:```html<!DOCTYPE html><html> <head> <meta charset="utf-8"> <title></title> <script> window.οnlοad=function(){ var oBtn1=document.getElementById('btn1');oBtn1.οnclick=function(){
var xhr=new XMLHttpRequest(); var formData=new FormData(); formData.set('a',12); xhr.open('post','1.php',true); xhr.send(formData); xhr.onreadystatechange=function(){ if(xhr.readyState==4){ if(xhr.status==200){ alert(xhr.responseText); }else{ alert('失败了') } } } } } </script> </head> <body> <input type="button" name="" value="ajax请求" id="btn1"> </body></html>```
```php<?phpecho $_POST['a']+$_POST['b']; ?>```二、formData文件上传
```html<!DOCTYPE html><html> <head> <meta charset="utf-8"> <title></title> <script> window.οnlοad=function(){ var oBtn=document.getElementById('btn1'); var oF1=document.getElementById('f1');oBtn.οnclick=function(){
var formData=new FormData(); formData.set('f1',oF1);var xhr=new XMLHttpRequest();
xhr.upload.οnlοad=function(){ console.log('上传成功') } xhr.upload.οnprοgress=function(ev){ console.log(ev.loaded+'/'+ev.total); }xhr.open('post','2.php',true);
xhr.send(formData); xhr.onreadystatechange=function(){ if(xhr.readyState==4){ alert(xhr.status) } } } } </script> </head> <body>
<input type="file" id="f1">
<input type="button" name="" value="ajax请求" id="btn1"> </body></html>```
0.formData.set('名字', file类型的input)1.xhr.upload.onload:上传完成2.xhr.upload.onprogress:进度变化三、CORS跨域<br>
1.如果是ajax1.0,添加res.setHeader('Access-Control-Allow-Origin','*');即可```JavasSriptconst http=require('http');let httpServer=http.createServer((req,res)=>{
res.setHeader('Access-Control-Allow-Origin','*'); res.write('aaaa'); res.end();});httpServer.listen(8080);
```
2.如果是ajax2.0,需要加上allowHosts.indexOf(req.headers['origin'])!=-1的判断
```JavasSriptconst http=require('http');let allowHosts=['taobao.com','baidu.com'];let httpServer=http.createServer((req,res)=>{ if(allowHosts.indexOf(req.headers['origin'])!=-1){ res.setHeader('Access-Control-Allow-Origin','*'); } res.write('aaaa'); res.end();});httpServer.listen(8080);
```