Fe-interview: [js] 第68天 formData主要是用来做什么的?它的操作方法有哪些?

Created on 22 Jun 2019  ·  5Comments  ·  Source: haizlin/fe-interview

第68天 formData主要是用来做什么的?它的操作方法有哪些?

js

Most helpful comment

用于后端参数处理为multipart/form-data的情况下 ,现在通常用于上传文件

All 5 comments

1、将form表单元素的name与value进行组合
2、异步上传表单

用于后端参数处理为multipart/form-data的情况下 ,现在通常用于上传文件

利用 FormData 对象,可以通过 JavaScript 键值对来模拟一系列表单控件,还可以使用 XMLHttpRequest的 send() 方法来异步提交表单。

可以利用formData来上传表单,或者提交上传的文件

document.getElementById('fileBtn').onchange = function () {

        //这是传入的内容是空
        var fm = new FormData();
        //给fm对象添加文件内容
        fm.append('icon',this.files[0]);

        //发送ajax请求
        var xhr = new XMLHttpRequest();
        //设置请求行
        xhr.open('post','getUrl.php');
        //发送数据
        xhr.send(fm);
        //监听事件完成
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4 && xhr.status == 200) {

                // console.log(xhr.responseText);
  document.querySelector('.imgShow').style.background = "url("+ xhr.responseText +") no-repeat center/cover";
            }
        }
    }

1、将form表单元素的name与value进行组合
2、异步上传表单

Was this page helpful?
0 / 5 - 0 ratings